0

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.

5
  • 3
    Does this answer your question? Accessing nested JavaScript objects and arrays by string path Commented Apr 13, 2022 at 10:02
  • @pilchard, I had a look on the answer but don't find the solution for my problem. Commented Apr 13, 2022 at 10:10
  • Every answer is a solution to your problem, you need to parse the string and then iteratively or recursively access the object. Another duplicate would be Javascript: Get deep value from object by passing path to it as string Commented Apr 13, 2022 at 10:13
  • @pilchard, my bad. there were too many tabs open and I looked at wrong tab. It has the answer on url suggested by you. However I would prefer short and simple solution by Ori. Commented Apr 13, 2022 at 10:40
  • 1
    The lodash solution is also included in the duplicates stackoverflow.com/a/31303609/13762301 Commented Apr 13, 2022 at 10:41

5 Answers 5

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Second answer in the linked duplicate stackoverflow.com/a/31303609/13762301
0

I would suggest accessing the nested value like this:

getData("Data").Value

2 Comments

I can't hardcode the .Value. It may have multilevel nested object and property names are dynamic.
You could access it like this too for one level of nesting: getData("Data")[someVar]
0

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'));

2 Comments

He said that he can't hardcode the key to get the data.
if it is dynamic send dynamic key to getData(). For example get keys from database and send it to getData()
0

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]])
}

Comments

0

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'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.