通过对象键合并对象数组 [英] Merge array of objects by object key

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

问题描述

鉴于上面的屏幕截图,我想通过"hand"属性合并此数组,以便最终结果为

Given the screenshot above I would like to merge this array by the "hand" attribute, so that the final result would be

[{hand: "KdAhAsKs", checkPct: 28, betPct: 72},{hand: "KcAhAsKs", checkPct: 28, betPct: 72}]

推荐答案

您可以使用 array#reduce 在与每个唯一 hand 相对应的对象中累积公共属性.然后使用 Object.values()取出所有值.

You can use array#reduce to accumulate the common property in an object corresponding to each unique hand and then take out all values using Object.values().

const data = [{hand: "KdAhAsKs", checkPct: 28}, {hand: "KdAhAsKs", betPct: 72},{hand: "KcAhAsKs", checkPct: 28}, { hand: "KcAhAsKs", betPct: 72}],
    result = Object.values(data.reduce((r,{hand, ...rest}) => {
      r[hand] = r[hand] || {hand};
      r[hand] = {...r[hand], ...rest};
      return r;
    },{}));
console.log(result);

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

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