Combining JSON Arrays
Posted
by George
on Stack Overflow
See other posts from Stack Overflow
or by George
Published on 2010-05-12T19:23:37Z
Indexed on
2010/05/12
20:14 UTC
Read the original article
Hit count: 254
I have 3 json arrays, each with information listed in the same format:
Array:
ID:
NAME:
DATA:
ID:
NAME:
DATA:
etc...
My goal is to combine all 3 arrays into one array, and sort and display by NAME by passing the 3 arrays into a function.
The function I've tried is:
JSCRIPT Call:
// to save time I'm just passing the name of the array, I've tried passing
// the full array name as json[0]['DATA'][array_1][0]['NAME'] as well.
combineNames(['array_1','array_2']);
FUNCTION:
function combineNames(names) {
var allNames = []
for (i=0;i<names.length;i++) {
for (j=0;j<json[0]['DATA'][names[i]].length;j++) {
allNames.push(json[0]['DATA'][names[i]][j]['NAME']);
}
}
return allNames.sort();
}
The above gives me the error that NAME is null or undefined.
I've also tried using the array.concat function which works when I hard code it:
var names = [];
var allNames = [];
var names = names.concat(json[0]['DATA']['array_1'],json[0]['DATA']['array_2']);
for (i=0;i<names.length;i++) {
allNames.push(names[i]['NAME']);
}
return allNames.sort();
But I can't figure out how to pass in the arrays into the function (and if possible I would like to just pass in the array name part instead of the whole json[0]['DATA']['array_name'] like I was trying to do in the first function...
© Stack Overflow or respective owner