0

I have two lists,

l1= ["apple","banana","grape"]
l2 = ["red","yellow","black"]

How to make a list of this type? (a list of objects)

l3 = [
   {fruit:"apple",colour:"red"},
   {fruit:"banana",colour:"yellow"},
   {fruit:"grape",colour:"balack"}
]

I tried something like this, but the output is not what I expected:

let l3 = [];
let Obj = {};
for (let l = 0;l<l1.length;l++) {
    Obj = {};
    for (h=0;h<l2.length;h++) {
        Obj["fruit"] = l1[h];
        Obj["colour"] = l2[h];
    }
    l3.push(Obj);
}
return l3;
0

2 Answers 2

4

You can use .map.

const l1 = ["apple", "banana", "grape"];
const l2 = ["red", "yellow", "black"];
const l3 = l1.map((fruit, index) => ({ fruit, color: l2[index] }));

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

Comments

2

You only need one loop, not nested loops.

for (let i = 0; i < l1.length; i++) {
    l3.push({fruit: l1[i], colour: l2[i]});
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.