0

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!

0

3 Answers 3

3

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));
Sign up to request clarification or add additional context in comments.

6 Comments

@PabloKarlsson Yup, no problem. JavaScript does not evaluate object keys, but does evaluate object values.
can you please elaborate it logic ..i didnt get it .
i have added a new key named "name" : "avinash" but it didnt display
@AvinashBabu What logic? Iterate over the keys of some, create result objects to hold the key and corresponding values from some and another, and add the result objects to an array. Note that the question states that the keys in both objects are identical.
how can we add if the keys are different ??
|
0

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

Comments

0

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)

1 Comment

It's definitely not what OP wants...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.