簡體   English   中英

匯總復雜的javascript對象屬性

[英]Sum complex javascript object properties

我有一個復雜的javascript對象。

var obj = {foo: {bar: {baz1 : {price: 200},baz2: {price: 300}}};

如何獲得價格屬性的總和? 謝謝

嘗試這個

var sum = 0;

for(var i in obj.foo.bar){

sum += obj.foo.bar[i].price;

}

console.log(sum);

這是另一個具有遞歸功能的函數。 有關詳細信息,請檢查getPriceSum()函數的代碼-魔術是通過reduce方法和遞歸調用完成的。

 var obj = { foo: { bar: { baz1: { price: 200 }, baz2: { price: 300 } } } }; var priceSum = getPriceSum(obj); console.log('Sum of prices is ' + priceSum); var obj = { foo: { price: 100, bar: { baz1: { price: 200 }, baz2: { price: 300 }, baz3: { price: 250 }, } } }; var priceSum = getPriceSum(obj); console.log('Another test - prices is ' + priceSum); function getPriceSum(obj) { var sum = Object.keys(obj).reduce(function(sum, prop) { if(typeof obj[prop] === 'object'){ return sum + getPriceSum(obj[prop]); } if(prop === 'price'){ return sum + obj[prop]; } }, 0); return sum; } 

jQuery的

var sum = 0

$.each(obj.foo.bar, function(index, value) {
    sum += value.price
}); 

console.log(sum)

僅Javascript:

var sum = 0

Object.keys(obj.foo.bar).map(function(objectKey, index) {
    var value = obj.foo.bar[objectKey];
    sum += value.price
});

console.log(sum)

您可以嘗試使用遞歸函數來查看每個屬性。

var sum = 0;
function recursive(obj) {
    $.each(obj, function(key, value) {
        if (typeof value === "object") { //is it an object?
            recursive(value);
        } else {
            sum += parseFloat(value); //if value is string, this will be 0
        }
    }
}

您可以使用兩步方法,即查找具有給定屬性名稱的所有值,然后匯總這些值。

 function getValues(object, key) { return Object.keys(object).reduce(function (r, k) { if (object[k] && typeof object[k] === 'object') { return r.concat(getValues(object[k], key)); } if (k === key) { r.push(object[k]); } return r; }, []); } var object = { foo: { bar: { baz1: { price: 200 }, baz2: { price: 300 } } } }, result = getValues(object, 'price').reduce((a, b) => a + b); console.log(result); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM