Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array of objects with multiple properties using javascript

How to create an array of objects that has two properties name and shade?

[{
    "name": "black",
    "shade": "dark"
  }, {
    "name": "white",
    "shade": "light"
  },
  {
    "name": "red",
    "shade": "dark"
  }, {
    "name": "blue",
    "shade": "dark"
  },
  {
    "name": "yellow",
    "shade": "light"
  }
]

I have two different arrays now.

name = ["black","white","red","blue","yellow"]
shade = ["dark","light","dark","dark","light"]

How can I achieve this?

like image 794
HKI345 Avatar asked Mar 07 '23 09:03

HKI345


2 Answers

Use map

var output = name.map( (s, i) => ({name : s, shade : shade[i]}) );

Demo

var name1 = ["black","white","red","blue","yellow"];

var shade = ["dark","light","dark","dark","light"];

var output = name1.map( (s, i) => ({name : s, shade : shade[i]}) );

console.log( output );
like image 55
gurvinder372 Avatar answered Mar 11 '23 23:03

gurvinder372


var new_array = [];
// assuming the arrays have the same length
for (var i = 0; i < name.length; i++)
    new_array.push({name: name[i], shade: shade[i]});
like image 30
Octavian Guzu Avatar answered Mar 11 '23 21:03

Octavian Guzu