将对象属性数组减少为嵌套对象

时间:2021-03-04 23:37:53

标签: javascript arrays reduce

我有一个越来越特殊的数组,例如。

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, {});

1 个答案:

答案 0 :(得分:3)

我会推荐一个简单的递归函数,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', 'americas', 'canada', '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', 'americas', 'canada', 'saskatchewan']    

const result =
  loc.reverse().reduce((val, key) => ({[key]: val}), "something")

console.log(result)

{
  "earth": {
    "americas": {
      "canada": {
        "saskatchewan": "something"
      }
    }
  }
}