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.

4

5 Answers 5

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

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

Comments

2

You can use Array.reduce()

var arr = ["name1", "name2", "name3"]
var obj = arr.reduce((acc, cur) => {
  acc[cur] = "";
  return acc;
}, {});
console.log(obj);

Comments

1

console.log(
  Object.fromEntries(
    ["name1", "name2", "name3"].map(name => [name, ''])
  )
)

Comments

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] = ''
}, {})

Comments

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.