将包含可能具有或不具有相同值的对象的单个数组简化为单个唯一对象的数组

时间:2018-08-30 17:08:54

标签: javascript arrays grouping javascript-objects

不太清楚如何简单地问这个问题。可以说我有一个这样的对象数组:

`{ 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: '' } ]`

我想要的是与任何其他键具有相同值的合并对象:

`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' }
]`

我一直在试图找到一个简单的解决方案。我知道一定有。我在循环中使用了spaghettified,并且使用了许多占位符var,感觉很不对

编辑: ...etc我的意思是成为更多相同类型的对象。在我的示例中,title属性是唯一一个可能存在具有相同键的对象的属性。如果有一个匹配的对象(包括匹配对象可能具有的属性),我希望它们成为一个对象。

编辑2:我已经包含了我正在使用的确切对象

1 个答案:

答案 0 :(得分:3)

您可以在一个对象中收集所有具有相同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; }