Home > database >  Nested object from an array using lodash in typescript
Nested object from an array using lodash in typescript

Time:04-30

My Data structure reads this

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

I want to create a object out of it like

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

What is best way to implement the nested part of it .

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

CodePudding user response:

Use Array.flatMap() to add the 'properties' key to the property array, concat the comparison, and then use Array.reduceRight() to create the object (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)

With lodash you can use the _.set() function:

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>

  • Related