0

Let's say I have this:

const myArr = ["NAME_A","NAME_B","NAME_C"];

And I'd like to convert it to:

const myObj = {
  NAME_A: null,
  NAME_B: null,
  NAME_C: null,
}

I can do it by initializing an empty object and adding properties by iterating the array with forEach or something, but I believe there is a more efficient solution out there.

cbdeveloper
  • 27,898
  • 37
  • 155
  • 336

2 Answers2

0

//I just used the indexes in the array as keys in the object *shrugs*
function arrToObj(arr){ //converting function
  let obj={}
  for(let i=0;i<arr.length;i++){
    obj[arr[i]]=null
  }
  return obj
}

const myArr = ["NAME_A","NAME_B","NAME_C"];
const myObj=arrToObj(myArr)
console.log(myObj)
The Bomb Squad
  • 4,192
  • 1
  • 9
  • 17
0

You can use inline queries to entries and create object from this entries like

Object.fromEntries(["NAME_A","NAME_B","NAME_C"].map((x)=>[x, null]))