J. Doe
J. Doe

Reputation: 13

javascript : Merge 2 arrays with property and index

I have 2 arrays like :

a1 = ["k1","k2","k3"];
a2 = ["v1","v2","v3"];

And I want that :

a3 = ["k1": { myv: "v1" }, "k2": { myv: "v2" }, "k3": { myv: "v3" }];

I used a forEach like :

a1.forEach(function(elem, i) {
  a3.push(elem);
  a3[i].name = a2[i];
});

But it doesn't works, It gives me :

a3 = ["k1","k2","k3"];

So how I can do this ?

Please help me.

Upvotes: 1

Views: 49

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386560

With a proper data structure and a single loop, you may need this:

var a1 = ["k1", "k2", "k3"],
    a2 = ["v1", "v2", "v3"],
    result = {};

a1.forEach(function (a, i) {
    result[a] = { myv: a2[i] };
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Upvotes: 3

Related Questions