首页 > 解决方案 > Reduce single array containing objects that may or may not have same value into an array of single unique objects

问题描述

Not quite sure how to ask this succinctly. Lets say I have an array of objects such that:

`{ title: 'The first title',
published_on: '2018-08-10 21:47:28',
body_content: '',
image_content: 'the first image'},
{ title: 'The first title',
published_on: '2018-08-10 21:47:28',
body_content: 'some content',
image_content: '' },
{ title: 'The second title',
published_on: '2018-08-06 17:08:28',
body_content: '',
image_content: 'an image url' },
{ title: 'The second title',
published_on: '2018-08-06 17:08:28',
body_content: 'a bunch of stuff',
image_content: '' } ]`

and what i'm after is the merged objects with the same value with any other keys:

`theArrayIWant = [
{ title: 'The first title',
published_on: '2018-08-10 21:47:28',
body_content: 'some content',
image_content: 'the first image' },
{ title: 'The second title',
published_on: '2018-08-06 17:08:28',
body_content: 'a bunch of stuff',
image_content: 'an image url' }
]`

I've been trying to find a simple solution for this. I know there must be. I am using spaghettified for loops and many placeholder vars and it just feels wrong

edit: The ...etc i meant to be more of the same type objects. In my example the title property is the only one where there might be an object with the same key. I want them to become a single object if there is a matching one including the properties the matching object might have.

edit 2: I've included the exact objects I'm working with

标签: javascriptarraysgroupingjavascript-objects

解决方案


您可以在单个对象中收集共享相同属性的所有title属性。

这是通过使用对象和title作为键来完成的。

var original = [{ title: "example name", image: "abcd" }, { title: "example name", content: "efgh" }, { title: "another name", image: "some image" }, { title: "another name", content: "some stuff" }],
    result = Object.values(original.reduce((r, o) => {
        Object.assign(r[o.title] = r[o.title] || {}, o);
        return r;
    }, {}));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

通过检查空元素来编辑更改的需求。

var original = [{ title: 'The first title', published_on: '2018-08-10 21:47:28', body_content: '', image_content: 'the first image' }, { title: 'The first title', published_on: '2018-08-10 21:47:28', body_content: 'some content', image_content: '' }, { title: 'The second title', published_on: '2018-08-06 17:08:28', body_content: '', image_content: 'an image url' }, { title: 'The second title', published_on: '2018-08-06 17:08:28', body_content: 'a bunch of stuff', image_content: '' }],
    result = Object.values(original.reduce((r, o) => {
        if (!r[o.title]) {
            r[o.title] = o;
            return r;
        }
        Object.entries(o).forEach(([k, v]) => v === '' || (r[o.title][k] = v));
        return r;
    }, {}));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读