Search code examples
javascriptlodash

Javascript data transformation


Input:

     {
    "8": [{
        "a": true,
        "b": {
            "xyz": 1
        }
    }, {
        "a": false,
        "b": {
            "xyz": 2
        }
    }],
    "13": [{
        "b": {
            "xyz": 4
        }
    }]
 }

Output:

    {
    "8": [{
        "b": {
            "xyz": 2
        }
    }]
 }

How can remove first element of each key and return the few keys of the same object using javascript and lodash library?


Solution

  • You could use reduce the entries returned by Object.entries() like this:

    let obj={"8":[{"a":!0,"b":{"xyz":1}},{"a":!1,"b":{"xyz":2}}],"13":[{"b":{"xyz":4}}]}
    
    let output = Object.entries(obj).reduce((acc, [key, value]) => {
      if(value.length > 1)
        acc[key] = value.slice(1)
      
      return acc;
    }, {})
    
    console.log(output)

    If you want to mutate the original object, loop through the object using for...in and use shift and delete like this:

    let obj={"8":[{"a":!0,"b":{"xyz":1}},{"a":!1,"b":{"xyz":2}}],"13":[{"b":{"xyz":4}}]}
    
    for (let key in obj) {
      obj[key].shift()
      if (obj[key].length === 0)
        delete obj[key]
    }
    
    console.log(obj)