Convert javascript array values to object keys with a default value - Stack Overflow

I'm a beginner playing with javascript and react. The problem I'm stuck with is that I have a

I'm a beginner playing with javascript and react. The problem I'm stuck with is that I have an array consisting of strings, and now I want to convert these strings to keys in an object so I can give them a value.

In other words: I have ["panel1", "panel2"] and I want to convert it to {"panel1":false,"panel2":false}.

After hours of searching, I managed to conjure up a working solution:

const names = ["panel1", "panel2"]
var initialState = {};
Object.keys(names).forEach((name) => initialState = { ...initialState,
  [names[name]]: false
})
console.log(JSON.stringify(initialState))

I'm a beginner playing with javascript and react. The problem I'm stuck with is that I have an array consisting of strings, and now I want to convert these strings to keys in an object so I can give them a value.

In other words: I have ["panel1", "panel2"] and I want to convert it to {"panel1":false,"panel2":false}.

After hours of searching, I managed to conjure up a working solution:

const names = ["panel1", "panel2"]
var initialState = {};
Object.keys(names).forEach((name) => initialState = { ...initialState,
  [names[name]]: false
})
console.log(JSON.stringify(initialState))

... but looping a function to dynamically expand the object like this seems very unelegant. What would be a better way of doing this? Note that I need my object to be in the same order as the array.

Share Improve this question asked Apr 26, 2020 at 16:27 SadBunnySadBunny 3661 gold badge5 silver badges15 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

The problem with yoru code is that the result of Object.keys(names) is the array ["0", "1"] (the keys of the array), not the names.

I'd use a for-of loop:

const initialState = {};
for (const name of names) {
    initialState[name] = false;
}

Or if you can't use ES2015+ features, a for loop:

var initialState = {};
for (var i = 0; i < names.length; ++i) {
    initialState[names[i]] = false;
}

Another approach is to use map to create an array of [name, value] arrays from your names array, then create the object using Object.fromEntries:

const initialState = Object.fromEntries(names.map(name => [name, false]));

map is from ES5, and Object.fromEntriees is quite new but easily polyfilled for older environments.

You can use Array.prototype.reduce to do this elegantly:

const names = ["panel1", "panel2"]
initialState = names.reduce((acc, name) => {
  acc[name] = false;
  return acc;
}, {});
console.log(JSON.stringify(initialState))

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744194930a4562610.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信