结合JSON数组

Cho*_*hoy 2 javascript json

我有3个json数组,每个数组都以相同的格式列出信息:

Array:
    ID:
    NAME:
    DATA:

    ID:
    NAME:
    DATA:

    etc...
Run Code Online (Sandbox Code Playgroud)

我的目标是将所有3个数组合并为一个数组,并通过将3个数组传递给函数来按NAME排序和显示.

我尝试过的功能是:

Javascript电话:

// 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']);
Run Code Online (Sandbox Code Playgroud)

功能:

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();
}
Run Code Online (Sandbox Code Playgroud)

上面给出了NAME为null或未定义的错误.

我也尝试使用array.concat函数,当我对其进行硬编码时它会起作用:

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();
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚如何将数组传递给函数(如果可能的话,我想传递数组名称部分而不是整个json [0] ['DATA'] ['array_name']像我试图在第一个功能...

vsy*_*ync 9

你可以轻松地将JSON与jQuery结合起来:

var x ={ a:1, b:2 };
var y ={ a:2, c:3 };
var z ={ b:3, d:4 };

$.extend(x, y, z);

console.dir(x); // now 'x' is all of them combined
Run Code Online (Sandbox Code Playgroud)