Search This Blog

2024/04/19

Javascript Interview Question:Search Keyword in Nexted JSON Object in keys or values

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:

function findInObject(multipleLevelNextedObject,
valueToBeFound,searchIn="values") {
const output = new Map();
function nextedObjectToArray(multipleLevelNextedObject) {
for (let key in multipleLevelNextedObject) {
if (typeof multipleLevelNextedObject[key] == "object") {
nextedObjectToArray(multipleLevelNextedObject[key]);
} else {
output.set(key,multipleLevelNextedObject[key])
}
}
}

nextedObjectToArray(multipleLevelNextedObject);

let isFound = false
let searchArray=[]
if(searchIn == "values"){
searchArray = Array.from(output.values())
}
if(searchIn == "keys"){
searchArray = Array.from(output.keys())
}
isFound = searchArray.includes(valueToBeFound)
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 seraching is",
JSON.stringify(multipleLevelNextedObject)
);
let searchIn ="values";//other value can be "keys"

let result = findInObject(multipleLevelNextedObject, valueToBeFound,searchIn)
? "found"
: "not found";

console.log(`keyword '${valueToBeFound}' ${result} in ${searchIn}
for given nexted object`);

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


Note:
Their is inbuild flat method over array,that need to pass depth till
which you want to flatten nexted array.If depth is passed as infinity
then it flatten till end.
E.g.

const nextedArray = [0, 1, [2, [3, [4, 5]]]];
console.log(nextedArray.flat(Infinity));

Output:
[ 0, 1, 2, 3, 4, 5 ]

You can use this code to search a keyword in keys or values of nexted object.

No comments:

Post a Comment