Get values by property name from an object at different levels
I have an object in the below format and I need to get all values from the Price
property at all levels of the object.
var o = {
Id: 1,
Price: 10,
Attribute: {
Id: 1,
Price: 2,
Modifier: {
Id: 34,
Price: 33
}
}
};
I was thinking of LinqToJS and jquery.map()
methods but I'd like to get a method as generic as possible. I tried this but it only works at the first level:
var keys = $.map(o, function(value, key) {
if (key == "Price") {
return value;
}
});
You can use a recursive function which tests the type of name of the property and its type. If it's name is Price
, add it to an array. If it's an object, recurse through that object to find a Price
key. Try this:
function getPrices(obj, arr) {
$.each(obj, function(k, v) {
if (k == "Price")
arr.push(v);
else if (typeof(v) == 'object')
getPrices(obj[k], arr);
});
return arr;
}
var prices = getPrices(o, []);
console.log(prices); // = [10, 2, 33]
Working example
您可以使用jQuery的$.map()
非常简单地执行此操作:
var o = {
Id: 1,
Price: 10,
Attribute: {
Id: 1,
Price: 2,
Modifier: {
Id: 34,
Price: 33
}
}
};
var res = $.map(o, function mapper(obj, key) {
return key === "Price" ? obj : $.map(obj, mapper)
});
document.querySelector("pre").textContent = JSON.stringify(res)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<pre></pre>
你可以使用for..in
循环,递归
var o = {
Id: 1,
Price: 10,
Attribute: {
Id: 1,
Price: 2,
Modifier: {
Id: 34,
Price: 33
}
}
};
var res = [];
(function re(obj) {
for (var prop in obj) {
if (prop === "Price") {
res.push(obj[prop])
} else {
re(obj[prop])
}
}
}(o));
console.log(res)
链接地址: http://www.djcxy.com/p/90782.html
上一篇: 给每个组的第一行添加一个等级
下一篇: 通过属性名称从不同级别的对象获取值