Home > Mobile >  Extract data from object based on key in JavaScript
Extract data from object based on key in JavaScript

Time:04-13

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.

CodePudding user response:

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>

CodePudding user response:

I would suggest accessing the nested value like this:

getData("Data").Value

CodePudding user response:

This is what you want. It is not matter how deep is your row. Try this. It would be multilevel nested object too. For example

Data.InnerData.Value...

const getData = (key) =>{
    let row = {isSelected: true, Data: {Id: '1A', Value: 'LD', InnerData: {Id: 1, Value: "Something"}}};
    var keys = key.split('.');
    var res = row;
    for(var i=0; i < keys.length; i  ){
        res = res[keys[i]];
    }
    
    return res;
}

console.log(getData('Data.InnerData.Value'));

CodePudding user response:

When you have dynamic object keys you can use javascript Object.keys method.

var data = getData("Data")
var dynamicKeys = Object.keys(data)

for(int i=0; i < dynamicKeys.length; i  ){
   console.log(data[dynamicKeys[i]])
}

CodePudding user response:

If you are certain that your object goes two level at most, you can try this simple solution

const isObject = (value) => {
   return typeof value === 'object' && !Array.isArray(value) && value !== null;
};

const testData = { isSelected: true, data: { id: '1A', value: 'LD' } };

const getData = (key) => {
   const keys = key.split('.');
   if (isObject(testData[keys[0]])) {
      return testData[keys[0]][keys[1]];
   }
   return testData[keys[0]];
};

console.log(getData('data.id'));
  • Related