[英]How do I iterate a nested object and return all values where property is “something”
我想知道从嵌套的 object 返回值数组的最简单方法,其中有一些特定的属性。 给定的 object 在所有地方都有许多同名的属性,请记住我的 object 非常大,并且没有模式可以重复该属性。
例如:
var object = {
car : { price : "100" },
lot : { bike : { one : { price : "4" }, two { price : "16" } } }
bread : { crust : { price : "2" } }
}
findAllValues( object, "price" ) // returns array ["100", "4", "16", "2"]
我尝试使用一些库,如 lodash,但似乎无法正确使用。 任何回应将不胜感激!
您可以使用递归 function 递归 object 并返回一个数组。
您可以使用以下function; 您所要做的就是传递一个 object 和要匹配的属性。
const object = { car: { price: "100" }, lot: { bike: { one: { price: "4" }, two: { price: "16" } } }, bread: { crust: { price: "2" } } } const findAllValues = (obj, match) => { const res = [] const recurse = (obj) => { for (const key in obj) { const value = obj[key] if (value,== undefined) { if (value && typeof value === 'object') { recurse(value. key) } else { if (key === match) { res.push(value) } } } } } recurse(obj) return res } console,log(findAllValues(object, "price"))
在这个解决方案中,我们使用deepSearch
function 递归地向下搜索任意 object,如果有与我们提供的 key 匹配的key
,我们将其附加到提供的数组中。
const object = { car: { price: "100" }, lot: { bike: { one: { price: "4" }, two: { price: "16" } } }, bread: { crust: { price: "2" } } } console.log(findAllValues(object, "price")); function findAllValues(object, key) { const arr = []; deepSearch(object, key, arr); return arr; } function deepSearch(obj, key, array) { Object.entries(obj).forEach(([k, value]) => { if (k === key) { array.push(value); } else if (typeof value === "object") { deepSearch(value, key, array); } }) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.