গভীর নেস্টেড অবজেক্ট থেকে নির্দিষ্ট কী 이름으로 সব ভ্যালু রিকার্শিভলি খুঁজে বের করা।
ডেটা স্ট্রাকচার
const people = {
Ram: {
fullName: 'Ram Kumar',
details: { age: 31, isEmployed: true }
},
Sourav: {
fullName: 'Sourav Singh',
details: { age: 22, isEmployed: false }
},
Jay: {
fullName: 'Jay Grewal',
details: { age: 26, isEmployed: true }
}
};
রিকার্সিভ সমাধান
const recursiveSearch = (obj, searchKey, results = []) => {
for (const key of Object.keys(obj)) {
const value = obj[key];
// কী মিলল এবং ভ্যালু অবজেক্ট নয়
if (key === searchKey && typeof value !== 'object') {
results.push(value);
}
// নেস্টেড অবজেক্ট হলে রিকার্শন
else if (value && typeof value === 'object') {
recursiveSearch(value, searchKey, results);
}
}
return results;
};
// টেস্ট
console.log(recursiveSearch(people, 'age')); // [31, 22, 26]
console.log(recursiveSearch(people, 'isEmployed')); // [true, false, true]
console.log(recursiveSearch(people, 'fullName')); // ['Ram Kumar', 'Sourav Singh', 'Jay Grewal']
console.log(recursiveSearch(people, 'address')); // [] (নেই)
ইটেরেটিভ ভার্সন (স্ট্যাক ব্যবহার)
const iterativeSearch = (obj, searchKey) => {
const results = [];
const stack = [obj];
while (stack.length > 0) {
const current = stack.pop();
for (const [key, value] of Object.entries(current)) {
if (key === searchKey && value !== null && typeof value !== 'object') {
results.push(value);
} else if (value && typeof value === 'object') {
stack.push(value);
}
}
}
return results;
};
অ্যাডভান্সড: পাথ সহ ফলাফল
const recursiveSearchWithPath = (obj, searchKey, path = '', results = []) => {
for (const [key, value] of Object.entries(obj)) {
const currentPath = path ? `${path}.${key}` : key;
if (key === searchKey && value !== null && typeof value !== 'object') {
results.push({ path: currentPath, value });
} else if (value && typeof value === 'object') {
recursiveSearchWithPath(value, searchKey, currentPath, results);
}
}
return results;
};
console.log(recursiveSearchWithPath(people, 'age'));
// [
// {path: 'Ram.details.age', value: 31},
// {path: 'Sourav.details.age', value: 22},
// {path: 'Jay.details.age', value: 26}
// ]
সময় জটিলতা
O(m × n) যেখানে m = চাইল্ড অবজেক্ট সংখ্যা, n = গভীরতম নেস্টিং লেভেল।
উৎপাদন
[ 31, 22, 26 ]