Reputation: 9
I have following object im not sure how to proceed.
How can I go through all objects and select the content array and search for a value x. And when the value x is in the object I need to get the object title from the object where the value was found.
Can anyone give me a hint how I can solve this problem?
Upvotes: 0
Views: 69
Reputation: 9808
you can use for...in to iterate over the object and indexOf()
to check if a key exists in the array content. something like this:
function searchVal(x){
for(var key in obj){
if(obj[key].hasOwnProperty('content') && obj[key].content.includes(x))
return key;
}
}
Upvotes: 1
Reputation: 138257
let name = Object.values( obj /*your main object*/ )
.find( obj => obj.content.includes(x) )
.name;
You could find the first object in the Objects values of your main obj, that has a property content which includes x, then get the name of that object.
Upvotes: 0
Reputation: 104775
You can use for...in
to iterate the object keys, then a regular for
loop to check the content
array for your specific value:
function findTitle(x) {
for (var key in obj) {
for (var i = 0; i < obj[key].content.length; i++) {
if (obj[key].content[i] === x) {
return key;
}
}
}
}
Upvotes: 1