0

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?

1
  • This is no valid JSON String, is it? Commented Aug 24, 2011 at 11:28

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 Quicker, more concise solution to my problem. Brevity FTW!
2

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

1 Comment

Thanks! Yeah, I mangled what I have above, but the data is in the form you described, so this should work. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.