最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Combining JSON Arrays - Stack Overflow

programmeradmin3浏览0评论

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 bine 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.

bineNames(['array_1','array_2']);

FUNCTION:

function bineNames(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...

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 bine 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.

bineNames(['array_1','array_2']);

FUNCTION:

function bineNames(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...

Share Improve this question edited May 12, 2010 at 20:35 skaffman 404k96 gold badges824 silver badges775 bronze badges asked May 12, 2010 at 19:23 ChoyChoy 2,11711 gold badges39 silver badges49 bronze badges 5
  • 1 Do you have the json array? It looks like there's a malformity in the JSON. – CodeJoust Commented May 12, 2010 at 19:26
  • Unfortunately, the data in the array isn't mine to share so I'm only able to give the structure. – Choy Commented May 12, 2010 at 19:35
  • Can you change the data or something? You've boggled me as to what this structure is. I'm visualising something along the lines of 3 arrays each containing something like this: [{ "id":1, "name":"Bob", "data":1},{ "id":2, "name":"Fred", "data":2 }]. Am I on the right track? – Matt Commented May 12, 2010 at 19:59
  • @Matt, you're absolutely correct. It's set up just like that. Each array consisting of several sub-arrays in the manner that you wrote out. – Choy Commented May 12, 2010 at 20:05
  • In which case, see my answer. – Matt Commented May 12, 2010 at 20:06
Add a ment  | 

4 Answers 4

Reset to default 9

you can bine JSON easily with 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 bined

If you've got 3 arrays like this:

[{ "id":1, "name":"Bob", "data":1},{ "id":2, "name":"Fred", "data":2 }]

Simply do:

function bine() {
    var ar = [];

    return ar.concat.apply(ar, arguments).sort(function (a, b) {
        var aName = a.NAME;
        var bName = b.NAME;
        if (aName < bName) {
            return -1;
        } else if (aName == bName) {
            return 0;
        } else {
            return 1;
        };
    });
};

Then call it like:

var jointArrays = bine(array1, array2, array3, ...);

However, if your JSON looks like this:

json[0]['DATA'][array_1]
json[0]['DATA'][array_2]
json[0]['DATA'][array_3]

You can simply define bine() as follows, which will be more convenient:

function bine(arrays) {
    var ar = [];

    return ar.concat.apply(ar, arrays).sort(function (a, b) {
        var aName = a.NAME;
        var bName = b.NAME;
        if (aName < bName) {
            return -1;
        } else if (aName == bName) {
            return 0;
        } else {
            return 1;
        };
    });
};

Then call it like:

var jointArrays = bine(json[0].DATA);

If you're wanting an array of just the names, rather than the objects, use the following:

function bine(arrays) {
    var ar = [],
        ret = [];

    ar = ar.concat.apply(ar, arrays);

    for (var i=0;i<ar.length;i++) {
        ret.push(ar.NAME);
    };

    return ret.sort();
};

Javascript is case sensitive; make sure it's DATA and not data, and NAME and not name.

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 var statement (and implied globals are bad). You should use:

for (var i=0;i<something.length;i++) {
   //
};

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 to object.one

Square notation is generally used when the key is stored as a variable, or when you're accessing an array.

var key = "one";
object[key]

Hope this helps.

You're redeclaring the allNames variable, emptying it.

Try this:

function bineNames(names) {
var allNames = [];
var data = json[0]['DATA'];
for (arrnames in data) {
    for (j=0;j<data[arrnames].length;j++) {
        if ('NAME' in data[arrnames]){
          allNames.push(data[arrnames]['NAME']);
        }
    }
}
return allNames.sort();
}
function allNames(names) {

var allNames = [];

for (var i=0;i<names.length;i++) {
    for (var j=0;j<json[0]['DATA'][names[i]].length;j++) {
        allNames.push(json[0]['DATA'][names[i]][j]['NAME']);
    }
}

return allNames.sort();

}

called using:

allNames(['array_1','array_2']);

Seems to work.

发布评论

评论列表(0)

  1. 暂无评论