Sharon
Sharon

Reputation: 3909

Adding to JSON array in JavaScript/jQuery

I have data being pulled in from various sources, each returning some form of JSON or similar, although, differently formatted each time. I need to get them all into one array, but I can't figure out how to do it.

The first set is an array like this:

[
 Object {id="70", type="ab", dateadded="12345678"},
 Object {id="85", type="ab", dateadded="87654321"}, ... more items ...
]

The second set is being pulled in from Facebook, and is like this:

[
 Object {id="12341234234", created_time="12345678"},
 Object {id="567856785678", created_time="87654321"}, ... more items ...
]

So, I need to alter the second set so that it has 'type', and it has 'dateadded' instead of 'created_time', and then I need to get this all into one array so it can be sorted on 'dateadded'.

How can I do this?

Upvotes: 0

Views: 13064

Answers (2)

mVChr
mVChr

Reputation: 50177

Assuming you have actual valid JSON instead of what you quoted above:

var jsonOld = '[{"id":"70","type":"ab","dateadded":"12345678"},{"id":"85","type":"ab","dateadded":"87654321"}]',
    jsonNew = '[{"id":"12341234234","created_time":"12345678"},{"id":"567856785678","created_time":"87654321"}]';

Then first parse these values into actual Javascript arrays:

var mainArr = JSON.parse(jsonOld),
    newArr = JSON.parse(jsonNew);

(If you already have actual Javascript arrays instead of JSON strings then skip the above step.)

Then just iterate over newArr and change the properties you need changed:

for (var i = 0, il = newArr.length; i < il; i++) {
    newArr[i].type = 'ab';
    newArr[i].dateadded = newArr[i].created_time;
    delete newArr[i].created_time;
}

And concatenate newArr into mainArr:

mainArr = mainArr.concat(newArr);

And sort on dateadded:

mainArr.sort(function(a, b) { return a.dateadded - b.dateadded; });

This will result in:

[{"id":"70","type":"ab","dateadded":"12345678"},
 {"id":"12341234234","type":"ab","dateadded":"12345678"},
 {"id":"85","type":"ab","dateadded":"87654321"},
 {"id":"567856785678","type":"ab","dateadded":"87654321"}]

See example

Upvotes: 2

DavidWainwright
DavidWainwright

Reputation: 2935

Use the first array's push() method:

// for each item in second array
    firstArray.push(convert(item));

function convert(obj) {
    // Convert obj into format compatible with first array and return it
}

Hope this helps.

Upvotes: 4

Related Questions