Search This Blog

2023/09/10

Javascript Interview Question:Search keyword in Nexted JSON Object Using Value Array

Problem Statement:
Given JSON object multiple level of nexting find given value exist
in it as value of some key.
E.g. Suppose our multiple level nexted object is

const myobj = {
a: "bangladesh",
b: {
c: "pakistan",
d: {
e: "nepal",
f: {
g: "india",
},
},
},
};
If we pass india we should get true,if we pass goa we should get false.

Solution:
const multipleLevelNextedObject = {
a: "bangladesh",
b: {
c: "pakistan",
d: {
e: "nepal",
f: {
g: "india",
},
},
},
};

let valueToBeFound = "goa";//also try passing india instead of goa

function findValueExistInJsonObject(multipleLevelNextedObject
, valueToBeFound) {
/*this function will create an array of all values at leaf level*/
function getValuesOfNextedObject(obj) {
let result = [];
for (let elt in obj) {
if (typeof obj[elt] == "object") {
result = result.concat(getValuesOfNextedObject(obj[elt]));
} else {
result.push(obj[elt]);
}
}
return result;
}

let valueArray = getValuesOfNextedObject(multipleLevelNextedObject);

let isValueFoundInNextedObjectValues = valueArray.find((elt) => {
if (elt == valueToBeFound) {
return true;
}
});

return isValueFoundInNextedObjectValues;
}


console.log("Multiple Level Nexted Object:",
JSON.stringify(multipleLevelNextedObject))
let isValueFoundInNextedObjectValues
= findValueExistInJsonObject(multipleLevelNextedObject,valueToBeFound)

if (isValueFoundInNextedObjectValues) {
console.log(`Value '${valueToBeFound}'
found in nexted object values`);
} else {
console.log(`Value '${valueToBeFound}'
not found in nexted object values`);
}
Output:
Multiple Level Nexted Object:
{"a":"bangladesh","b":{"c":"pakistan","d":{"e":"nepal","f":{"g":"india"}}}}
Value 'goa' not found in nexted object values

No comments:

Post a Comment