求和复杂的javascript对象属性

时间:2017-08-04 06:36:57

标签: javascript

我有一个复杂的javascript对象。

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

如何获得价格属性的总和? 感谢

5 个答案:

答案 0 :(得分:2)

试试这个

var sum = 0;

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

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

}

console.log(sum);

答案 1 :(得分:0)

这是另一个递归的函数。有关详细信息,请查看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;
}

答案 2 :(得分:0)

的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)

答案 3 :(得分:0)

您可以尝试使用递归函数来查看每个属性。

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
        }
    }
}

答案 4 :(得分: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);