sergey_c
sergey_c

Reputation: 761

Convert two objects into one array (JavaScript)

I have 2 JS(json) obects with identical keys:

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

I need to convert it into

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

So, this is the question.
Thanks!

Upvotes: 0

Views: 473

Answers (3)

TRONGBAO
TRONGBAO

Reputation: 1

An easy way is to double push if you have a little object like that

const ob1 = {
  "id1": "some1",
  "id2": "some2",
  "id3": "some3"
}
const ob2 = {
  "id1": "another1",
  "id2": "another2",
  "id3": "another3"
}
let array = []
array.push(ob1)
array.push(ob2)
console.log(array)

Upvotes: 0

Pablo Jomer
Pablo Jomer

Reputation: 10378

This should work provided each id exists in each hash.

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]});
}

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97120

Here you go:

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));

Upvotes: 3

Related Questions