用对象的JavaScript数组中的键值之和分组

时间:2019-08-20 17:09:02

标签: javascript arrays json

我有一个像下面这样的对象数组

var data = [{monthName: "Jun", name:'web', number: 1, month: 6}, 
{monthName: "Jul", name:'web', number: 2, month: 7},
{monthName: "Aug", name:'web', number: 2, month: 8}, 
{monthName: "Jun", name:'sales', number: 12, month: 6}, 
{monthName: "Jul", name:'sales', number: 2, month: 7}]

我想根据键“名称”对数据进行分组,然后需要将数字作为数组获取。

示例输出如下

datasets: [{
     name: 'web',
     number: [1, 2, 2],
       },{
    name: 'sales',
    number: [12, 2]
         }]

我不确定如何对数据进行分组,然后获取键值作为数组。

我已使用以下代码对数据进行分组

result = data.reduce(function (r, a) {
             r[a.name] = r[a.name] || [];
             r[a.name].push(a);
        return r;
    }, Object.create(null));

但不确定如何获得所需的输出。有人可以帮我吗?

4 个答案:

答案 0 :(得分:1)

在精简的同时,如果键还不存在,还可以建立所需的结果对象:

  const result = [];
  { // Make hash viable to GCing after this operation
    const hash = Object.create(null);
    for(const { name, number } of data) {
       if(!hash[name])
         result.push({ name, numbers: hash[name] = [] });
       hash[name].push(number);
    }
  }

答案 1 :(得分:1)

您需要检查数组中是否包含带有name的对象,如果存在,则将数字附加到该对象上,否则请推送一个新对象:

var data = [
  { monthName: "Jun", name: "web", number: 1, month: 6 },
  { monthName: "Jul", name: "web", number: 2, month: 7 },
  { monthName: "Aug", name: "web", number: 2, month: 8 },
  { monthName: "Jun", name: "sales", number: 12, month: 6 },
  { monthName: "Jul", name: "sales", number: 2, month: 7 }
];

var result = data.reduce((acc, curr) => {
  const ndx = acc.findIndex(e => e.name === curr.name);

  if (ndx > -1) {
    acc[ndx].number.push(curr.number);
  } else {
    acc.push({
      name: curr.name,
      number: [curr.number]
    });
  }

  return acc;
}, []);

console.log(result);

答案 2 :(得分:1)

您的回答几乎是正确的,只需添加另一行以推送到number数组即可:

var data = [{monthName: "Jun", name: 'web', number: 1, month: 6},
	{monthName: "Jul", name: 'web', number: 2, month: 7},
	{monthName: "Aug", name: 'web', number: 2, month: 8},
	{monthName: "Jun", name: 'sales', number: 12, month: 6},
	{monthName: "Jul", name: 'sales', number: 2, month: 7}];

result = Object.values(data.reduce(function (r, {name, number}) {
	r[name] = r[name] || {name, number: []};
	r[name].number.push(number);
	return r;
}, {})).map((v, i) => ({...v, iteration: i + 1}));

console.log(result);

答案 3 :(得分:1)

创建一个映射,该映射将@Component public class AuthFilter implements WebFilter { final static String KEY_HEADER_1 = "Name of header one"; final static String KEY_HEADER_2 = "Name of header two"; @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); HttpHeaders headers = request.getHeaders(); if(headers.get(KEY_HEADER_1) == null || headers.get(KEY_HEADER_2) == null) { throw new ResponseStatusException(HttpStatus.UNAUTHORIZED); } return chain.filter(exchange); } } 的条目分组,然后使用reduce获取该映射的条目,并使用Object.entries对其进行迭代,从而为流程中的每个对象创建一个新对象

map