0

I'm working on a reactjs web app I have an array like

let arr = ["name","message", etc...];

I want to convert it to object but to look like

let desired = { name:'', message:'' };

I tried a few things but none of them worked.

2
  • 7
    I tried few things but none worked ? can you show code you have tried so far ? Commented May 27, 2019 at 5:36
  • 2
    reactjs shouldn't be tagged here as the problem in consideration has nothing to do with reactjs. Commented May 27, 2019 at 5:41

3 Answers 3

3

If you just want to assign each value in the array the value of an empty string, use reduce:

let arr = ["name","message", "etc"];
let desired = arr.reduce((acc, curr) => (acc[curr] = "", acc), {});
console.log(desired);
.as-console-wrapper { max-height: 100% !important; top: auto; }

ES5 syntax:

var arr = ["name","message", "etc"];
var desired = arr.reduce(function(acc, curr) {
  acc[curr] = "";
  return acc;
}, {});
console.log(desired);
.as-console-wrapper { max-height: 100% !important; top: auto; }

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

1 Comment

No problem @zewo, always glad to help.
1

Try this:

let arr = ["name","message", "etc"];
let desired = {};
for (let i = 0; i < arr.length; i++) {
    desired[arr[i]] = "";
}
console.log(desired);

Comments

0

You can also use forEach()

let arr = ['name', 'type', 'id', 'phone'];
let obj = {};
arr.forEach(i=>{obj[i] = ''});

console.log(obj);

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.