根据属性值减少对象数组 [英] Reduce an Array of object based on value of attribute

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

问题描述

我正在尝试根据对象内部的公共属性(category.blocktitle)值从现有的对象数组创建一个新的对象数组。我的对象数组看起来像这样。

I am trying to create a new array of object from an existing array of object based on the common attribute (category.blocktitle) value inside the object. My array of object looks like this.

[
  {
    "category": {
      "name": "test1111",
      "val": "test111111111",
      "blocktitle": ".test.0"
    }
  },
  {
    "category": {
      "name": "test22",
      "val": "test2222",
      "blocktitle": ".test.0.test2"
    }
  },
  {
    "category": {
      "name": "test1111111",
      "val": "test11111111111",
      "blocktitle": ".test.0"
    }
  },
  {
    "category": {
      "name": "test2222",
      "val": "test222222",
      "blocktitle": ".test.0.test2"
    }
  }
]

我想要的输出是

[
  {
    "category": {
       "name_val" : [
              {
                     "name": "test1111",
                     "val": "test111111111"
              }, 
              { 
                     "name": "test1111111",
                     "val": "test11111111111",
              }
       ]
    },
    "blocktitle": ".test.0"
  },
  {
    "category": {
        "name_val" : [
                  {
                         "name": "test22",
                         "val": "test2222"
                  }, 
                  { 
                         "name": "test2222",
                         "val": "test222222",
                  }
        ]
    },
    "blocktitle": ".test.0.test2"
  }
]

我尝试过reduce / map / filter但不确定我做错了什么。

I have tried reduce / map / filter but not sure what I am doing wrong.

推荐答案

我会使用ES6 Array.prototype.reduce Array.prototype.filter 方法:

I would use ES6 Array.prototype.reduce and Array.prototype.filter methods:

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

其中数据是您的初始数据数组。

Where data is your initial data array.

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

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