Search This Blog

2024/04/19

Javascript Interview Question:Search keyword in Nexted JSON Object Using Array of non-nexted Objects

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:

Using Array of non-nexted object

function findValueInObject(multipleLevelNextedObject, valueToBeFound) {
let output = [];
function nextedObjectToArray(multipleLevelNextedObject) {
for (let key in multipleLevelNextedObject) {
if (typeof multipleLevelNextedObject[key] == "object") {
nextedObjectToArray(multipleLevelNextedObject[key]);
} else {
let item = {};
item[key] = multipleLevelNextedObject[key];
output.push(item);
}
}
}

nextedObjectToArray(multipleLevelNextedObject);

let isFound = false;
output.forEach((obj) => {
let keys = Object.keys(obj);
let value = obj[keys[0]];
if (value == valueToBeFound) {
isFound = true;
return;
}
});

return isFound;
}

//driver code
const multipleLevelNextedObject = {
a: "bangladesh",
b: {
c: "pakistan",
d: {
e: "nepal",
f: {
g: "india",
},
},
},
};
let valueToBeFound = "india";
console.log("The nexted object in we which we are searching is",
JSON.stringify(multipleLevelNextedObject))
let result = findValueInObject(multipleLevelNextedObject, valueToBeFound)
?'found':'not found';

console.log(`value '${valueToBeFound}' is ${result} in nexted object`);

Output:
The nexted object in we which we are seraching is
{"a":"bangladesh","b":{"c":"pakistan","d":{"e":"nepal","f":{"g":"india"}}}}
value 'india' is found in nexted object

No comments:

Post a Comment