I have the following code which returns whether the key and value are found in an array object.
function iterate(array, prop, val) {
Object.keys(array).forEach((key) => {
if (key === prop && val === array[key]) {
console.log(`key: ${key}, value: ${array[key]}`);
}
if (typeof array[key] === 'object') {
iterate(array[key], prop, val);
}
});
}
That's ok but now I would like to access the full content of that specific object where those properties and values were found. This is my JSON:
[
{
"page":"main",
"content":[
{
"type":"item",
"item":[
{
"name":"HAMMER",
"price":"1000"
},
{
"name":"SWORD",
"price":"2000"
}
]
}
]
}
]
This is what I look for/get with my function:
"name":"HAMMER"
And this is what I need:
{
"name":"HAMMER",
"price":"1000"
},
Is there any way to achieve that or am I addressing this problem from the wrong perspective?
You could use a basic loop, to find an item from deep nested object...
let data = [{ "page": "main", "content": [{ "type": "item", "item": [{ "name": "HAMMER", "price": "1000" }, { "name": "SWORD", "price": "2000" }] }] }]
let [prop, value] = ["name", "HAMMER"]
loop: for (let page of data) {
for (let type of page.content) {
let found = type.item.find(v => v[prop] === value);
if (found) {
console.log(found)
break loop;
}
}
}
would you like to lookup recursively? Then you can use a generator...
let data = [{ "page": "main", "content": [{ "type": "item", "item": [{ "name": "HAMMER", "price": "1000" }, { "name": "SWORD", "price": "2000" }] }] }]
function* iterate(arrayLike, prop, value) {
for (let page of arrayLike) {
if (page[prop] == value)
yield page;
for (let v of Object.values(page)) {
if (Array.isArray(v))
yield* iterate(v, prop, value)
}
}
}
for (let item of iterate(data, "name", "HAMMER")) {
console.log(item)
}