如何解决将对象属性数组减少为嵌套对象
const locationProperties = ['earth','americas','canada','saskatchewan'];
我想要一个对象:
{
earth: {
americas: {
canada: {
saskatchewan: {
// data
}
}
}
}
}
我想使用 .reduce
创建对象,但在 reducer 中应用转换后,我只剩下 {}
const reducer = (accumulator,item) => {
accumulator[item] = {};
return accumulator[item];
}
const reducedArray = locationProperties.reduce(reducer,{});
解决方法
我会推荐一个简单的递归函数,nest
-
const nest = ([key,...more],val) =>
key == null
? val
: {[key]: nest(more,val)}
const loc =
['earth','americas','canada','saskatchewan']
console.log(nest(loc,"something"))
{
"earth": {
"americas": {
"canada": {
"saskatchewan": "something"
}
}
}
}
您也可以使用 reduceRight
-
const loc =
['earth','saskatchewan']
const result =
loc.reduceRight((val,key) => ({[key]: val}),"something")
console.log(result)
{
"earth": {
"americas": {
"canada": {
"saskatchewan": "something"
}
}
}
}
既然您熟悉 reduce
,我将指出 arr.reduceRight(...)
实际上等效于 arr.reverse().reduce(...)
。但是在这种情况下使用 reduceRight
效率更高,并且不会改变输入数组 -
const loc =
['earth','saskatchewan']
const result =
loc.reverse().reduce((val,"something")
console.log(result)
{
"earth": {
"americas": {
"canada": {
"saskatchewan": "something"
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。