有一个很好的数组方法reduce()从数组中获取一个值。例子:

[0,1,2,3,4].reduce(function(previousValue, currentValue, index, array){
  return previousValue + currentValue;
});

在对象上实现同样效果的最佳方法是什么?我想这样做:

{ 
    a: {value:1}, 
    b: {value:2}, 
    c: {value:3} 
}.reduce(function(previous, current, index, array){
  return previous.value + current.value;
});

但是,Object似乎没有实现任何reduce()方法。


当前回答

试试这个。它将对来自其他变量的数字进行排序。

const obj = {
   a: 1,
   b: 2,
   c: 3
};
const result = Object.keys(obj)
.reduce((acc, rec) => typeof obj[rec] === "number" ? acc.concat([obj[rec]]) : acc, [])
.reduce((acc, rec) => acc + rec)

其他回答

1:

[{value:5}, {value:10}].reduce((previousValue, currentValue) => { return {value: previousValue.value + currentValue.value}})

>> Object {value: 15}

2:

[{value:5}, {value:10}].map(item => item.value).reduce((previousValue, currentValue) => {return previousValue + currentValue })

>> 15

3:

[{value:5}, {value:10}].reduce(function (previousValue, currentValue) {
      return {value: previousValue.value + currentValue.value};
})

>> Object {value: 15}

一个对象可以通过以下方法转换为数组:object .entries(), object .keys(), object .values(),然后被还原为数组。但是,您也可以在不创建中间数组的情况下缩减对象。

我创建了一个小的帮助库odict用于处理对象。

npm install --save odict

它有一个类似于Array.prototype.reduce()的reduce函数:

export const reduce = (dict, reducer, accumulator) => {
  for (const key in dict)
    accumulator = reducer(accumulator, dict[key], key, dict);
  return accumulator;
};

你也可以把它分配给:

Object.reduce = reduce;

因为这个方法非常有用!

所以你问题的答案是:

const result = Object.reduce(
  {
    a: {value:1},
    b: {value:2},
    c: {value:3},
  },
  (accumulator, current) => (accumulator.value += current.value, accumulator), // reducer function must return accumulator
  {value: 0} // initial accumulator value
);

由于它还没有在答案中得到证实,因此下划线的减少也适用于此。

_.reduce({ 
    a: {value:1}, 
    b: {value:2}, 
    c: {value:3} 
}, function(prev, current){
    //prev is either first object or total value
    var total = prev.value || prev

    return total + current.value
})

注意,_。如果列表对象只有一项,Reduce将返回唯一的值(对象或其他),而不调用迭代器函数。

_.reduce({ 
    a: {value:1} 
}, function(prev, current){
    //not called
})

//returns {value: 1} instead of 1

一种选择是减少键():

var o = { 
    a: {value:1}, 
    b: {value:2}, 
    c: {value:3} 
};

Object.keys(o).reduce(function (previous, key) {
    return previous + o[key].value;
}, 0);

有了这个,你会想要指定一个初始值,或者第一轮将是'a' + 2。

如果你想将结果作为对象({value:…}),你必须每次初始化并返回对象:

Object.keys(o).reduce(function (previous, key) {
    previous.value += o[key].value;
    return previous;
}, { value: 0 });

你可以使用生成器表达式(多年来所有浏览器都支持,Node中也支持)来获取列表中的键-值对:

>>> a = {"b": 3}
Object { b=3}

>>> [[i, a[i]] for (i in a) if (a.hasOwnProperty(i))]
[["b", 3]]