在打字稿中使用lodash从数组中嵌套对象

Nested object from an array using lodash in typescript

我的数据结构读取这个

{property: ["a","b"] , value : "somevalue" , comparision : "somecomparison"}

我想用它创建一个对象,比如

{
 "properties": {
    "a": {
      "properties": {
         "b": {
            "somecomparision": "somevalue"
            }
          }
        }
      }
    }   

实现嵌套部分的最佳方法是什么。

  {
      properties: {
        [property[0]: {
          [comparison]: value,
        },
      },
    }

使用Array.flatMap()将'properties'键添加到property数组,concat比较,然后使用Array.reduceRight()创建对象(TS playground):

const fn = ({ property, value, comparision }) =>
  property
    .flatMap(p => ['properties', p])
    .concat(comparision)
    .reduceRight((acc, p) => ({ [p]: acc }), value)

const obj = {property: ["a","b"] , value : "somevalue" , comparision : "somecomparison"}

const result = fn(obj)

console.log(result)

对于 lodash,您可以使用 _.set() 函数:

const fn = ({ property, value, comparision }) => 
  _.set(
    {}, 
    _.flatMap(property, p => ['properties', p]).concat(comparision),
    value
  )
  
const obj = {property: ["a","b"] , value : "somevalue" , comparision : "somecomparison"}

const result = fn(obj)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>