Skip to content Skip to sidebar Skip to footer

Get An Object With Null Values From An Array Of Nested Objects

I have an array of nested objects. How do I get an object with null values using only a particular key in the array of objects? The code works good, but is there a way to optimize

Solution 1:

In the headersMap you can create the object with the null value { [onClick]: null }. Now you can spread the array of objects into _.assign() to convert them to a single object.

const headers = [{"title":"Arun","id":"arunId","onClick":"onClickArun"},{"title":"George","id":"georgeId","onClick":"","children":[{"title":"David","id":"davidId","onClick":"onClickDavid"},{"title":"Patrick","id":"patrickId","onClick":"onClickPatrick"}]},{"title":"Mark","id":"markId","onClick":"onClickMark"}];

constheadersMap = ({ onClick, children }) =>
  onClick ? 
    { [onClick]: null } // create the object with a null value
    : 
    _.flatMap(children, headersMap); // use flatMap to handle multiple levelsconst headerObj = _.assign({}, ..._.flatMap(headers, headersMap)); // spread and mergeconsole.log(headerObj)
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

Solution 2:

You could use reduce method to create recursive function that will return object as a result and search for target key on any level.

let headers = [{"title":"Arun","id":"arunId","onClick":"onClickArun"},{"title":"George","id":"georgeId","onClick":"","children":[{"title":"David","id":"davidId","onClick":"onClickDavid"},{"title":"Patrick","id":"patrickId","onClick":"onClickPatrick"}]},{"title":"Mark","id":"markId","onClick":"onClickMark"}]

functionget(prop, data) {
  return data.reduce((r, e) => {
    if (e[prop]) r[e[prop]] = null;
    if (e.children) Object.assign(r, get(prop, e.children))
    return r;
  }, {})
}

const result = get('onClick', headers)
console.log(result)

Post a Comment for "Get An Object With Null Values From An Array Of Nested Objects"