Sunday 15 May 2011

Javascript working with complex arrays -



Javascript working with complex arrays -

i have 1 array of objects, customerorder array. each object in array contains customerid. multiple orders have same customerid. i have sec array of objects, client array. my goal take each object customerorder array , sort them smaller arrays grouped customerid can create each of individual smaller arrays value in key/value pair in client array.

here 1 object in each of 2 arrays looks like.

customerorderarray = ( { orderid: '', ordertype: '', customerid: '' }) customerarray = ( { id: '', customername: '', customercity: '' })

here code have tried. results in 1 orderobject beingness attached lastly customerobject iterates through.

(var k = 0; k < customerorderarray.length; k++) { (j = 0; j < customerarray.length; j++) { alljobs = new array(); if (customerarray[j].id == customerorderarray[k].customerid) { if("alljobs" in customerarray[j]) { customerarray[j].alljobs.push(customerorderarray[k]); } else { customerarray[j].alljobs.push(customerorderarray[k]); } break; } } }

if there can expand on help clarify problem or if explanation on broader image may help allow me know. may approaching problem wrong. appreciate help can get. give thanks in advance.

if have understand correctly, want result object customerid beingness key , value beingness object holding name, city , alljobs belongs key.

var orderlength = customerorderarray.length, customlength = customerarray.length, customerobject = {}; (var = 0; < customlength; i++) { // iterate on customerarray var cai = customerarray[i], id = cai.id, // create value-object name, city , empty alljobs-array val = {name: cai.customername, city: cai.customercity, alljobs: []}; // iterate on customerorderarray find orders belonging id (var o, j = 0; j < orderlength; j++) { o = customerorderarray[j]; // if id same force job alljobs if (o.customerid == id) val.alljobs.push(o); } // insert client customerobject, key id , value val customerobject[id] = val; }

so if have client id 'user25' , 2 jobs, customerobject['user25'] gives:

{ name: 'ben', city: 'new york', alljobs: [ {orderid: 123, ordertype: 'mail', customerid: 'user25'}, {orderid: 124, ordertype: 'phone', customerid: 'user25'} ] }

the original arrays not changed. if customerorderarray may emptied during runtime can done bit faster.

if have misunderstood or doesn't fit otherwise please post critique.

javascript arrays

No comments:

Post a Comment