使用reduce在JavaScript中添加集合对象的属性值

时间:2018-06-06 21:03:00

标签: javascript

非常直接:

var bar = [
  { a: 10, b: 20 }, { a: 10, b: 20 }
];

var reduce = bar.reduce((acc, item) => {
  acc['a'] = item.a++;
  acc['b'] = item.b++
  return acc;
}, {});

 console.log(reduce);
 {a: 10, b: 20}

我希望减少分配参考:{a:20, b: 40}

3 个答案:

答案 0 :(得分:1)

您应该添加到现有累加器的属性值,而不是将累加器属性指定为项的属性递增1。在给定此实现的情况下,您也不应将初始对象传递给reduce(或者,如果您这样做,则需要定义ab属性)

由于您正在使用reduce,我认为您还应该考虑使用const代替var - const更不容易出错并且更容易阅读:



const bar = [
  { a: 10, b: 20 }, { a: 10, b: 20 }
];
const reduced = bar.reduce((acc, item) => {
  acc.a += item.a;
  acc.b += item.b;
  return acc;
});
 console.log(reduced);




答案 1 :(得分:1)

这是一个通用的解决方案,即使你的数组​​中的对象包含不同的属性也能正常工作。



import socket
import os
import csv
import subprocess
name = {}
CI = {}
hostname = {}
status = {}
with open('Output1.csv', 'r', newline='') as csvinput:
    reader = csv.DictReader(csvinput)

    for rows in reader:
        CI = rows['CI_Name']
        try:
            ip = socket.gethostbyname(CI)
        except socket.error:
            pass
        name = socket.getfqdn(CI)
        data = name

        hostname = rows['CI_Name']
        response = subprocess.Popen(['ping.exe',hostname], stdout = subprocess.PIPE).communicate()[0]
        response = response.decode()
        print(response)
        if 'bytes=32' in response:
            status = 'Up'
        elif 'destination host unreachable' in response:
            status = 'Unreachable'
        else:
            status = 'Down'
        if status == 'Down':
            ip = 'Not Found'
        with open('Output Final.csv', 'a', newline='') as csvoutput:
            output = csv.writer(csvoutput)
            output.writerow([hostname] + [data] + [status] + [ip])




答案 2 :(得分:0)

您可以返回带有附加值的新对象。



var bar = [{ a: 10, b: 20 }, { a: 10, b: 20 }],
    reduce = bar.reduce((a, b) => ({ a: a.a + b.a, b: a.b + b.b }));

console.log(reduce);




或者对所有属性采用完整的动态方法。



const add = (a, b) =>
        Object.assign({}, a, ...Object.entries(b).map(([k, v]) => ({ [k]: a[k] + v })));
var bar = [{ a: 10, b: 20 }, { a: 10, b: 20 }],
    reduce = bar.reduce(add);

console.log(reduce);