Convert array of strings into an object with those string as properties and null values

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.

24 thoughts on “Convert array of strings into an object with those string as properties and null values”

  1. //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)
    Reply

Leave a Comment