JavaScript-按键减少对象数组 [英] JavaScript - Reduce Array of Objects by Key

查看:45
本文介绍了JavaScript-按键减少对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用一系列对象,如:

const arr = [
  {name: "qewregf dqewafs", value: "qewregf dqewafs answer", count: 2},
  {name: "survey with select", value: "survey with select answer", count: 2},
  {name: "werasd", value: "Donald", count: 1},
  {name: "werasd", value: "Jim", count: 1}
];

我正在尝试根据name键的匹配值减少数组,并实现所需的输出,如:

I am trying to reduce the array on matching values for the name key and achieve an desired output like:

desiredOutput = [
  {name: "qewregf dqewafs", data: [{value: "qewregf dqewafs answer", count: 2}]},
  {name: "survey with select", data: [{value: "survey with select answer", count: 2}]},
  {name: "werasd", data: [{value: "Donald", count: 1}, {value: "Jim", count: 1}]}
]

这种尝试减少了数组,但是我不知道如何在不覆盖的情况下合并嵌套值.

This attempt reduces the array, but I am missing how to merge the nested values without overwriting.

const arr = [{"name":"qewregf dqewafs","value":"qewregf dqewafs answer","count":2},{"name":"survey with select","value":"survey with select answer","count":2},{"name":"werasd","value":"Donald","count":1},{"name":"werasd","value":"Jim","count":1}];

const result = arr.reduce((acc, d) => {
  const found = acc.find(a => a.name === d.name);
  const value = { name: d.name, val: d.value };
  if (found) {
    acc.push(...value);
  }
  else {
    acc.push({ name: d.name, data: [{ value: d.value }, { count: d.count }] });
  }
  return acc;
}, []);

console.log(result);

我想念什么?

推荐答案

您的代码有点接近目标,只需要进行一些调整即可.

You codes are a little close to the goal, just need to adjust something.

请在下面的演示中查看评论:

Please see the comment in below demo:

  1. acc.find没有找到任何内容时,则推入一个元素{name:d.name, data: [value]}

  1. When acc.find doesn't find anything, then push one element {name:d.name, data: [value]}

(如果找到),然后将一个{value: ...}推入data属性.

if found, then push one {value: ...} into data property.

const arr = [
  {name: "qewregf dqewafs", value: "qewregf dqewafs answer", count: 2},
  {name: "survey with select", value: "survey with select answer", count: 2},
  {name: "werasd", value: "Donald", count: 1},
  {name: "werasd", value: "Jim", count: 1}
];

const result = arr.reduce((acc, d) => {
  const found = acc.find(a => a.name === d.name);
  //const value = { name: d.name, val: d.value };
  const value = { value: d.value, count: d.count }; // the element in data property
  if (!found) {
    //acc.push(...value);
    acc.push({name:d.name, data: [value]}) // not found, so need to add data property
  }
  else {
    //acc.push({ name: d.name, data: [{ value: d.value }, { count: d.count }] });
    found.data.push(value) // if found, that means data property exists, so just push new element to found.data.
  }
  return acc;
}, []);

console.log(result)

这篇关于JavaScript-按键减少对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆