0

Input:

var array = [["make", "BMW"], ["model","X6"], ["year",2020]];

My Output should be like this:

var object = {
  make : “BMW”
  model : “X6”,
  year : 2020
}
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
Aasin
  • 11
  • 2
  • If you don't mind using `Map`, that is exactly the format the constructor takes.. eg.. `var m = new Map(array);`. `console.log(m.make);` => `BMW` – Keith Mar 18 '20 at 16:26

2 Answers2

1

const array = [["make", "BMW"], ["model","X6"], ["year",2020]]; 

let obj={}
for(let item of array){
obj[item[0]]=item[1]
}
console.log(obj)
  • Why create new object in every loop instead of simply assigning `obj[item[0]] = item[1]` – adiga Mar 18 '20 at 16:44
  • @adiga modified answer. Doesn't spread operator append new `key-val` pair to same obj? – Prakash Reddy Potlapadu Mar 18 '20 at 17:02
  • 1
    You are creating new object literal `{...obj, [item[0]]:item[1] }` and reassigning the variable `obj`. Spread is useful when you don't want to mutate the `obj`. Since you are reassigning back to `obj` there is no need for it here. – adiga Mar 19 '20 at 05:06
0

You can use Object.fromEntries()

const arr = [["make", "BMW"], ["model","X6"], ["year",2020]];
const res = Object.fromEntries(arr);
console.log(res)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73