Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to combine two arrays into an array of objects?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;

>Solution :

You only need one loop, not nested loops.

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading