从条目创建嵌套对象
Creating a nested object from entries
有没有办法从条目中生成嵌套的 JavaScript Object
?
Object.fromEntries()
不太会做,因为它不做嵌套对象。
const entries = [['a.b', 'c'], ['a.d', 'e']]
// Object.fromEntries(entries) returns:
{
'a.b': 'c',
'a.d': 'e',
}
// whatIAmLookingFor(entries) returns:
{
a: {
b: 'c',
d: 'e',
}
}
我想我找到了使用 lodash
的方法:
import set from 'lodash/set'
const result = {}
const entries = [['a.b', 'c'], ['a.d', 'e']]
entries.forEach((entry) => {
const key = entry[0]
const value = entry[1]
set(result, key, value)
})
您可以减少数组 entries
并减少键。然后用最后一个key给最终对象赋值。
const
setValue = (object, [key, value]) => {
const
keys = key.split('.'),
last = keys.pop();
keys.reduce((o, k) => o[k] ??= {}, object)[last] = value;
return object;
},
entries = [['a.b', 'c'], ['a.d', 'e']],
result = entries.reduce(setValue, {});
console.log(result);
有没有办法从条目中生成嵌套的 JavaScript Object
?
Object.fromEntries()
不太会做,因为它不做嵌套对象。
const entries = [['a.b', 'c'], ['a.d', 'e']]
// Object.fromEntries(entries) returns:
{
'a.b': 'c',
'a.d': 'e',
}
// whatIAmLookingFor(entries) returns:
{
a: {
b: 'c',
d: 'e',
}
}
我想我找到了使用 lodash
的方法:
import set from 'lodash/set'
const result = {}
const entries = [['a.b', 'c'], ['a.d', 'e']]
entries.forEach((entry) => {
const key = entry[0]
const value = entry[1]
set(result, key, value)
})
您可以减少数组 entries
并减少键。然后用最后一个key给最终对象赋值。
const
setValue = (object, [key, value]) => {
const
keys = key.split('.'),
last = keys.pop();
keys.reduce((o, k) => o[k] ??= {}, object)[last] = value;
return object;
},
entries = [['a.b', 'c'], ['a.d', 'e']],
result = entries.reduce(setValue, {});
console.log(result);