Merge array of objects with underscore

家住魔仙堡 提交于 2020-01-02 21:57:20

问题


I have array of objects like this. And they have duplicated property 'contactName' values

[
    {
        categoryId:1
        categoryName:"Default"
        contactId:141
        contactName:"Anonymous"
        name:"Mobile"
        value:"+4417087654"
    },
    {
        categoryId:1
        categoryName:"Default"
        contactId:325
        contactName:"Anonymous"
        name:"Email"
        value:"test2@gmail.com"
    },
    {
        categoryId:1
        categoryName:"Default"
        contactId:333
        contactName:"Anonymous"
        name:"Email"
        value:"ivdtest@test.com"
    }
]

I want to merge them in one object by the name of property 'contactName' To something like this

[
    {
        categoryId: 1,
        categoryName: "Default",
        contactId: 141,
        contactName: "Anonymous",
        names: {
            1: "Mobile",
            2: "Email",
            3: "Email"
        },
        values: {
            1: '+2234324',
            2: "ivdtest@test.com",
            3: "test2@gmail.com"
        }
    }
];

Edit: How can I group objects also by categoryName ?


回答1:


var grouped = _.groupBy(input, 'contactName');
var output = _.map(grouped, function(entries) {
  return _.extend(
    _.pick(entries[0], 'categoryId', 'categoryName', 'contactId', 'contactName'), 
    {
      names: _.indexBy(_.pluck(entries, 'name'), function(val, index) { return index +1; }), 
      values: _.indexBy(_.pluck(entries, 'value'), function(val, index) { return index +1; })
    }
  );
});

https://jsfiddle.net/f1x4tscu/3/




回答2:


Another variant with array inside the object

var grouped = _.groupBy(this.contacts, 'contactName');
var output = _.map(grouped, function (entries) {
    return _.extend(
        _.pick(entries[0], 'categoryId', 'categoryName', 'contactId', 'contactName'),
        {
            addresses: _.map(entries, function (m) {
                return {
                    name: m.name,
                    value: m.value
                }
            }),
        }
    );
});


来源:https://stackoverflow.com/questions/40111744/merge-array-of-objects-with-underscore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!