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 badges2 Answers
Reset to default 7The 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条)