1

I'm struggling to group array as a key to an object.

var a = ["fruit1", "fruit2", "fruit3"]
var b = ["apple", "banana", "Orange"];
var obj = {};
a.forEach((x) => {
    b.forEach((y) => {

        obj[x] = y;
    })

})
console.log(obj)

OUTPUT:

{​fruit1:apple,fruit2:banana:fruit3:orange}​
1
  • Could any one help me.. Commented Jun 26, 2021 at 14:42

3 Answers 3

2

In the inner loop you rewrite all object values with the last element of b. Try this to utilize the index argument of .forEach():

var a = ["fruit1", "fruit2", "fruit3"];
var b = ["apple", "banana", "Orange"];
var obj = {};

a.forEach((x, i) => {
  obj[x] = b[i];
});

console.log(obj)

Sign up to request clarification or add additional context in comments.

Comments

1

You could build an array of entries and then an object from it.

const
    keys = ["fruit1", "fruit2", "fruit3"],
    values = ["apple", "banana", "Orange"],
    result = Object.fromEntries(keys.map((key, i) => [key, values[i]]));

console.log(result);

Comments

1

You can use zipObj function from ramda library which convert your arrays to an object just like below:

const a = ["fruit1", "fruit2", "fruit3"]
const b = ["apple", "banana", "Orange"];
const obj = R.zipObj(a, b) //{"fruit1": "apple", "fruit2": "banana", "fruit3": "Orange"}
console.log(obj)

Comments

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.