将两个对象转换为一个数组(JavaScript)

时间:2014-07-30 08:32:21

标签: javascript arrays

我有两个具有相同键的JS(json)对象:

{"id1" : "some1", "id2" : "some2", "id3" : "some3"}
{"id1" : "another1", "id2" : "another2", "id3" : "another3"}

我需要将其转换为

[
    {
        "id" : "id1",
        "some" : "some1",
        "another" : "another1"
    },
    {
        "id" : "id2",
        "some" : "some2",
        "another" : "another2"
    },
    {
        "id" : "id3",
        "some" : "some3",
        "another" : "another3"
    }
]

所以,这就是问题 谢谢!

2 个答案:

答案 0 :(得分:3)

Here你去了:

var some = {"id1" : "some1", "id2" : "some2", "id3" : "some3"};
var another = {"id1" : "another1", "id2" : "another2", "id3" : "another3"};

var result = [];
for (var id in some) {
    result.push({
        id: id,
        some: some[id],
        another: another[id]
    });
}

alert(JSON.stringify(result));

答案 1 :(得分:0)

如果每个哈希中都存在每个id,这应该可以工作。

var ids = {"id1" : "some1", "id2" : "some2", "id3" : "some3"};
var ids2 = {"id1" : "another1", "id2" : "another2", "id3" : "another3"};
a= [];
for (var id in ids) {
  a.push({id: id, some:ids[id], another : ids2[id]});
}
相关问题