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:
Javascript 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…
If you’ve got 3 arrays like this:
Simply do:
Then call it like:
However, if your JSON looks like this:
You can simply define
combine()as follows, which will be more convenient:Then call it like:
If you’re wanting an array of just the names, rather than the objects, use the following:
Javascript is case sensitive; make sure it’s
DATAand notdata, andNAMEand notname.Now for a little bit of housekeeping.
In your example, both of your counter variables are being declared as “implied globals”, because you’re not prefixing them with the
varstatement (and implied globals are bad). You should use:Instead of neglecting the
var.Also, “{}” creates an object. “[]” creates an array. Javascript does not support associative array’s; e.g array’s with keys that are anything except a number. What you’re JSON is returning is an array of objects
“Square notation” and “dot notation” are interchangeable.
object["one"]is equivalent toobject.oneSquare notation is generally used when the key is stored as a variable, or when you’re accessing an array.
Hope this helps.