-4

I have an array like this:

var arr = [
  ["1", "tony stark"],
  ["2", "steve rogers"],
  ["3", "thor"],
  ["4", "nick fury"]
];

I want the values from the array to be written to a object like this

var obj = [
  {id:"1", name:"tony stark"},
  {id:"2", name:"steve rogers"},
  {id:"3", name:"thor"},
  {id:"4", name:"nick fury"}
];
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
  • 3
    Possible duplicate of [Javascript string array to object](https://stackoverflow.com/questions/49418242/javascript-string-array-to-object) and [Converting string array to Name/Value object in javascript](https://stackoverflow.com/questions/6074608) – adiga Mar 15 '19 at 12:34
  • 2
    You can use array map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map – PaulShovan Mar 15 '19 at 12:35

2 Answers2

3

You could destucture the array and build a new object with short hand properties.

var array = [["1", "tony stark"], ["2", "steve rogers"], ["3", "thor"], ["4", "nick fury"]],
    result = array.map(([id, name]) => ({ id, name }));
 
console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

You can map on your array and create your object

const arr = [
  ["1", "tony stark"],
  ["2", "steve rogers"],
  ["3", "thor"],
  ["4", "nick fury"]
];


var obj = arr.map((info) => {
  return {
    id: info[0],
    name: info[1]
  };
})

console.log(obj)
R3tep
  • 12,512
  • 10
  • 48
  • 75