Search code examples
javascriptlodash

Extract data from object based on key in JavaScript


I am trying to find the property value of an object based on key. I have below function getData which returns the data based on key passed as input parameter.

const getData = (key) => {
  let row = {isSelected: true, Data: {Id: '1A', Value: 'LD'}};
  return row[key];
}
console.log(getData('Data'));

In normal scenario it is working fine but how can I get the property value from nested object Data.Value.

If I call getData function as getData('Data.Value'), It should return LD.


Solution

  • You can use lodash's _.get() function that returns the value at a path:

    const getData = path => {
      const row = {isSelected: true, Data: {Id: '1A', Value: 'LD', InnerData: {Id: 1, Value: "Something"}}};
        
      return _.get(row, path);
    }
    
    console.log(getData('Data'));
    console.log(getData('Data.Value'));
    console.log(getData('Data.InnerData.Value'));
    <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>