1

I have a Javascript object that I am trying to make. This object is meant to have named values based on an array of strings.

So I want to convert an array like this:

var arr = ["name1", "name2", "name3"]

Into an object like this:

var obj = {
    name1: "",
    name2: "",
    name3: ""
}

It seems obvious to me that I can't simply pull the name of the previous variables to get the name of the parameter since the name appears to be hard coded. Anything similar to my question answers how to fill in the value, not the name. I assume if worse comes to worse, I could use the "eval" function, but that seems to add a lot of complexity to something that seems relatively straightforward.

Parker.R
  • 88
  • 8
  • Here is solution for you https://stackoverflow.com/questions/4215737/convert-array-to-object – Joko Joko Dec 01 '20 at 19:47
  • @JokoJoko, this is just providing values to an object when I'm looking to provide names instead. – Parker.R Dec 01 '20 at 19:51
  • I gave new answer of possible solutions. Try them. – Joko Joko Dec 01 '20 at 20:00
  • Does this answer your question? [How do I convert array of Objects into one Object in JavaScript?](https://stackoverflow.com/questions/19874555/how-do-i-convert-array-of-objects-into-one-object-in-javascript) – Adnan Ahmed Dec 01 '20 at 20:09

5 Answers5

2

You can use Array.reduce()

var arr = ["name1", "name2", "name3"]
var obj = arr.reduce((acc, cur) => {
  acc[cur] = "";
  return acc;
}, {});
console.log(obj);
wangdev87
  • 8,611
  • 3
  • 8
  • 31
2

Just map arrays with key/value and create an object from the entries.

const
    array = ["name1", "name2", "name3"],
    object = Object.fromEntries(array.map(k => [k, '']));

console.log(object);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

console.log(
  Object.fromEntries(
    ["name1", "name2", "name3"].map(name => [name, ''])
  )
)
Nino Filiu
  • 16,660
  • 11
  • 54
  • 84
0

You can use for of and construct the object like this:

const arr = ["name1", "name2", "name3"]
let obj

for(const value of arr) {
    obj[value] = ''
}

console.log(obj)

Or you can use reduce:

const arr = ["name1", "name2", "name3"]
const obj = arr.reduce((acc, cur) => {
    acc[cur] = ''
}, {})

Hugh
  • 366
  • 1
  • 12
0

Check this: Javascript string array to object

Or try this, found from converting string array into javascript object:

function strings_to_object(array) {

  // Initialize new empty array
  var objects = [];


  // Loop through the array
  for (var i = 0; i < array.length; i++) {

    // Create the object in the format you want
    var obj = {array[i]};

    // Add it to the array
    objects.push(obj);
  }

  // Return the new array
  return objects;
}
Joko Joko
  • 111
  • 2
  • 16