how do we search a json object using a string?

To get the value with the key in Object, you can use Object[key] (here, key is variable name) and this will return the value of the selected key.

return configData.rootData[data]?.testData0; // Javascript case

So instead of using {{ }}, replace it with square brackets and you will get the result.

And on the above code, rootData[data]?.testData0 has same meaning as rootData[data] ? rootData[data].testData0 : undefined so this will be needed for validation check. (unexpected data value input)

On Typescript,

if (data in configData.rootData && "testData0" in configData.rootData[data]) {
  return configData.rootData[data].testData0;
} else {
  return undefined;
}

const input = {
  "rootData": {
    "test1": {
      "testData0": "Previous data",
      "testData1": "Earlier Data"
    },
    "test2": {
      "testData0": "Partial data",
      "testData1": "Services data"
    },
    "test3": {
      "testData0": "Regular data",
      "testData1": {
        "testData0": "Your package"
      }
    }
  }
};

let data = 'test1';
console.log(input.rootData[data]?.testData0);

data = 'test2';
console.log(input.rootData[data]?.testData0);

data = 'test3';
console.log(input.rootData[data]?.testData0);

data = 'test4';
console.log(input.rootData[data]?.testData0);

data = 'test5';
if (data in input.rootData) {
  console.log('Existed', input.rootData[data].testData0);
} else {
  console.log('Not Existed');
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top