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.

4
  • 3
    Does this answer your question? Convert array to object keys Commented Feb 18, 2021 at 16:48
  • 1
    @Aristotle Yes! Commented Feb 18, 2021 at 16:49
  • 1
    Nina will come up with something, hold on Commented Feb 18, 2021 at 16:49
  • one loop using each index value of the array as a key for the new object seems to work shrugs Commented Feb 18, 2021 at 17:50

2 Answers 2

1

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

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

Comments

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)

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.