-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"}
];
2

2 Answers 2

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);

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

Comments

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)

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.