Search code examples
javascriptobjectlodash

Get a nested value with lodash


I'm trying to retrieve a nested value from an object by the given key. I've made it working with two simple forEach loops but I like to use a more... functional approach to this problem.

Here is the code I've got so far:

const object = {
  screen: {
    '[data-id="123"]': {
      'font-family': 'Arial',
    },
    '[data-id="456"]': {
      'background-color': 'red',
      'font-family': 'Comic Sans',
    },
  },
};

const prop = 'font-family';
const props = [];

forEach(object, (selectors) => {
  forEach(selectors, (selector) => {
    if (prop in selector) {
      props.push(selector[prop]);
    }
  });
});

console.log(props);

In this case, the function returns an array of font families (indicated by the prop const).

I'm looking to using lodash functions like map and reduce but I don't really know where to start.

Thanks in advance.


Solution

  • Since this is a nested object it would really depend on how you want to tackle this. If you use the map in a nested fashion, you will end up with a nested array. To match your output the nested array can be flattened.

    _.flatten(_.map(object, (prop) => _.map(prop, (nestedProp) => nestedProp['font-family'])));
    

    But if you don't want to use reduce instead of flatten then you could reduce the nested array from the array

    _.reduce(_.map(object, (prop) => _.map(prop, (nestedProp) => nestedProp['font-family'])),(a, b) => [...a, ...b]);
    

    At this point I think readability is taking some hit. As you can see nested map functions can get messy.