有一个很好的Array方法reduce()
来从Array中获取一个值。例如:
[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()
方法。
答案 0 :(得分:254)
一个选项是reduce
keys()
:
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 });
答案 1 :(得分:35)
ES6实施: Object.entries()
const o = {
a: {value: 1},
b: {value: 2},
c: {value: 3}
};
const total = Object.entries(o).reduce(function (total, pair) {
const [key, value] = pair;
return total + value;
}, 0);
答案 2 :(得分:16)
首先,你没有得到reduce之前的值。
在您的伪代码中,您有return previous.value + current.value
,因此previous
值将是下次调用时的数字,而不是对象。
其次,reduce
是一个Array方法,而不是Object的方法,当你迭代一个对象的属性时,你不能依赖它的顺序(参见:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...in,这是也适用于Object.keys;所以我不确定在对象上应用reduce
是否有意义。
但是,如果订单不重要,您可以:
Object.keys(obj).reduce(function(sum, key) {
return sum + obj[key].value;
}, 0);
或者你只能map对象的值:
Object.keys(obj).map(function(key) { return this[key].value }, obj).reduce(function (previous, current) {
return previous + current;
});
P.S。在ES6中使用胖箭头函数的语法(已经在Firefox Nightly中),你可以缩小一点:
Object.keys(obj).map(key => obj[key].value).reduce((previous, current) => previous + current);
答案 3 :(得分:12)
在这种情况下,您真正想要的是Object.values
。这是一个简洁的 ES6 实现,记住了这一点:
add = {
a: {value:1},
b: {value:2},
c: {value:3}
}
total = Object.values(add).reduce((t, n) => t + n.value, 0)
console.log(total) // 6
或简单地说:
add = {
a: 1,
b: 2,
c: 3
}
total = Object.values(add).reduce((t, n) => t + n)
console.log(total) // 6
答案 4 :(得分:3)
扩展Object.prototype。
Object.prototype.reduce = function( reduceCallback, initialValue ) {
var obj = this, keys = Object.keys( obj );
return keys.reduce( function( prevVal, item, idx, arr ) {
return reduceCallback( prevVal, item, obj[item], obj );
}, initialValue );
};
使用样本。
var dataset = {
key1 : 'value1',
key2 : 'value2',
key3 : 'value3'
};
function reduceFn( prevVal, key, val, obj ) {
return prevVal + key + ' : ' + val + '; ';
}
console.log( dataset.reduce( reduceFn, 'initialValue' ) );
'Output' == 'initialValue; key1 : value1; key2 : value2; key3 : value3; '.
n'Joy它,伙计们! ; - )
答案 5 :(得分:2)
您可以使用生成器表达式(在所有浏览器中支持多年,在Node中)以获取可以减少的列表中的键值对:
>>> a = {"b": 3}
Object { b=3}
>>> [[i, a[i]] for (i in a) if (a.hasOwnProperty(i))]
[["b", 3]]
答案 6 :(得分:2)
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}
答案 7 :(得分:1)
如果可以使用数组,请使用数组,数组的长度和顺序是它的一半。
function reducer(obj, fun, temp){
if(typeof fun=== 'function'){
if(temp== undefined) temp= '';
for(var p in obj){
if(obj.hasOwnProperty(p)){
temp= fun(obj[p], temp, p, obj);
}
}
}
return temp;
}
var O={a:{value:1},b:{value:2},c:{value:3}}
reducer(O, function(a, b){return a.value+b;},0);
/ *返回值:(Number) 6 * /
答案 8 :(得分:1)
这不是很难自己实现:
function reduceObj(obj, callback, initial) {
"use strict";
var key, lastvalue, firstIteration = true;
if (typeof callback !== 'function') {
throw new TypeError(callback + 'is not a function');
}
if (arguments.length > 2) {
// initial value set
firstIteration = false;
lastvalue = initial;
}
for (key in obj) {
if (!obj.hasOwnProperty(key)) continue;
if (firstIteration)
firstIteration = false;
lastvalue = obj[key];
continue;
}
lastvalue = callback(lastvalue, obj[key], key, obj);
}
if (firstIteration) {
throw new TypeError('Reduce of empty object with no initial value');
}
return lastvalue;
}
行动中:
var o = {a: {value:1}, b: {value:2}, c: {value:3}};
reduceObj(o, function(prev, curr) { prev.value += cur.value; return prev;}, {value:0});
reduceObj(o, function(prev, curr) { return {value: prev.value + curr.value};});
// both == { value: 6 };
reduceObj(o, function(prev, curr) { return prev + curr.value; }, 0);
// == 6
您也可以将它添加到Object原型中:
if (typeof Object.prototype.reduce !== 'function') {
Object.prototype.reduce = function(callback, initial) {
"use strict";
var args = Array.prototype.slice(arguments);
args.unshift(this);
return reduceObj.apply(null, args);
}
}
答案 9 :(得分:1)
由于尚未在答案中确认,Underscore的reduce
也适用于此。
_.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
答案 10 :(得分:1)
尽管可以使用Object.entries(),Object.keys(),Object.values()方法将其转换为数组表示形式,然后将其还原为通常的数组,但我不希望创建中间数组,仅用于遍历对象,以节省内存和周期!
因此,我创建了一个非常类似于Array.prototype.reduce()的辅助函数。
const {hasOwnProperty} = Object.prototype;
const reduce = (object, reducer, accumulator) => {
for (const key in object)
if (hasOwnProperty.call(object, key))
accumulator = reducer(accumulator, object[key], key, object);
return accumulator;
};
您也可以将其分配给
Object.reduce = reduce;
因为此方法非常有用!
因此,您的问题的答案将是:
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
);
答案 11 :(得分:0)
试用此一个划线箭头功能
Object.values(o).map(a => a.value, o).reduce((ac, key, index, arr) => ac+=key)
答案 12 :(得分:0)
尝试这个。它将对其他变量中的数字进行排序。
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)
答案 13 :(得分:-1)
如果作为数组处理就容易多了
返回水果总量:
let fruits = [{ name: 'banana', id: 0, quantity: 9 }, { name: 'strawberry', id: 1, quantity: 1 }, { name: 'kiwi', id: 2, quantity: 2 }, { name: 'apple', id: 3, quantity: 4 }]
let total = fruits.reduce((sum, f) => sum + f.quantity, 0);