Die*_*uks 6 javascript linq jquery json object
我有一个以下格式的对象,我需要从该Price属性的所有级别获取所有值.
var o = {
Id: 1,
Price: 10,
Attribute: {
Id: 1,
Price: 2,
Modifier: {
Id: 34,
Price: 33
}
}
};
Run Code Online (Sandbox Code Playgroud)
我在考虑LinqToJS和jquery.map()方法,但我想尽可能地获得通用的方法.我试过这个,但它只适用于第一级:
var keys = $.map(o, function(value, key) {
if (key == "Price") {
return value;
}
});
Run Code Online (Sandbox Code Playgroud)
您可以使用递归函数来测试属性名称的类型及其类型。如果它的名称是Price,则将其添加到数组中。如果它是一个对象,则递归该对象以查找键Price。尝试这个:
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]
Run Code Online (Sandbox Code Playgroud)