I have a nested array of objects and I'm trying to find a string inside of it. Once I find it I'd like to return the containing object. Here's my code:
const myArray = [{
label: "Home",
last: "odlir",
children: [{
label: "Home 1",
last: "odlir1",
children: [{
label: "Home 2",
last: "odlir2"
}, {
label: "Home 3",
last: "odlir3"
}]
},
{
label: "Home 4",
last: "odlir4",
children: [{
label: "Home 5",
last: "odlir5"
}, {
label: "Home 6",
last: "odlir6"
}]
}
]
},
{
label: "dash",
last: "gom"
},
{
label: "principal",
last: "asd"
}
];
function contain(obj, string) {
if (obj == null)
return false;
if (obj.last == string)
return obj;
if (typeof obj.children == 'undefined')
return false;
for (let i = 0; i < obj.children.length; i++) {
if (contain(obj.children[i], string))
return obj;
}
return false;
}
function getObject(array, string) {
for (let i = 0; i < array.length; i++) {
if (contain(array[i], string)) {
return array[i];
}
}
}
console.log('test', getObject(myArray, 'odlir6'));
I'm getting back the object I want, parent object and even grandfather. Here's is a stackblitz of this code: https://stackblitz.com/edit/js-hgchmx
-
what do you want by arrays? the index or the outer array?Nina Scholz– Nina Scholz2020年02月27日 21:51:23 +00:00Commented Feb 27, 2020 at 21:51
-
2Does this answer your question? JavaScript recursive search in JSON objectHeretic Monkey– Heretic Monkey2020年02月27日 21:51:48 +00:00Commented Feb 27, 2020 at 21:51
-
@HereticMonkey Thanks i'm going to try that answerRildo Gomez– Rildo Gomez2020年02月27日 21:54:56 +00:00Commented Feb 27, 2020 at 21:54
-
@NinaScholz actually i want the object that contains the string i'm looking forRildo Gomez– Rildo Gomez2020年02月27日 21:56:34 +00:00Commented Feb 27, 2020 at 21:56
1 Answer 1
You could take a recursive approach and store the paren object for every nested call.
Declare
result, later this variable contains the parent object.Check if the given variable is not
nullbut an object. Exit if not.Iterate the values from the object with a short circuit and
- check if the value is equal to the wanted string, then return with the assignment of the object.
- otherwise return the result of the recursive call.
function getObject(object, string) {
var result;
if (!object || typeof object !== 'object') return;
Object.values(object).some(v => {
if (v === string) return result = object;
return result = getObject(v, string);
});
return result;
}
const
array = [{ label: "Home", last: "odlir", children: [{ label: "Home 1", last: "odlir1", children: [{ label: "Home 2", last: "odlir2" }, { label: "Home 3", last: "odlir3" }] }, { label: "Home 4", last: "odlir4", children: [{ label: "Home 5", last: "odlir5" }, { label: "Home 6", last: "odlir6" }] }] }, { label: "dash", last: "gom" }, { label: "principal", last: "asd" }];
console.log(getObject(array, 'odlir6'));