[英]How to get an object from one key,value in array
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:
这是我的 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) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.