我有一组具有相同属性的对象。如何将具有相同 period
属性的对象合并到新的对象数组中。我在 stackoverflow 中看到了示例,但它们大多使用 JQuery 或 lodash 等外部库。我可以用 vanilla.js 做这个吗?
<强> Here 是带有代码和期望值标记的 Plunkr。谢谢您的帮助
最佳答案
您可以将其与日期分组并使用对象作为对哈希表的引用。另一个对象用于访问 day/nicht 属性。
var array = [{ period: '01.07.2016', count: 11, scale: 'd' }, { period: '01.07.2016', count: 22, scale: 'n' }, { period: '01.08.2016', count: 33, scale: 'n' }, { period: '01.08.2016', count: 44, scale: 'd' }, { period: '01.09.2016', count: 55, scale: 'd' }, { period: '01.09.2016', count: 66, scale: 'n' }],
grouped = [];
array.forEach(function (a) {
var day = a.period.slice(3, 5);
if (!this[day]) {
this[day] = { date: day, day: 0, night: 0 };
grouped.push(this[day]);
}
this[day][{ d: 'day', n: 'night' }[a.scale]] += a.count;
}, Object.create(null));
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
您也可以在哈希表上使用闭包,而不使用 thisArg
。
var array = [{ period: '01.07.2016', count: 11, scale: 'd' }, { period: '01.07.2016', count: 22, scale: 'n' }, { period: '01.08.2016', count: 33, scale: 'n' }, { period: '01.08.2016', count: 44, scale: 'd' }, { period: '01.09.2016', count: 55, scale: 'd' }, { period: '01.09.2016', count: 66, scale: 'n' }],
grouped = [];
array.forEach(function (hash) {
return function (a) {
var day = a.period.slice(3, 5);
if (!hash[day]) {
hash[day] = { date: day, day: 0, night: 0 };
grouped.push(hash[day]);
}
hash[day][{ d: 'day', n: 'night' }[a.scale]] += a.count;
};
}(Object.create(null)));
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
没有滥用 thisArg
和 IFFE 的干净版本
var array = [{ period: '01.07.2016', count: 11, scale: 'd' }, { period: '01.07.2016', count: 22, scale: 'n' }, { period: '01.08.2016', count: 33, scale: 'n' }, { period: '01.08.2016', count: 44, scale: 'd' }, { period: '01.09.2016', count: 55, scale: 'd' }, { period: '01.09.2016', count: 66, scale: 'n' }],
grouped = function () {
var result = [],
hash = Object.create(null);
array.forEach(function (a) {
var day = a.period.slice(3, 5);
if (!hash[day]) {
hash[day] = { date: day, day: 0, night: 0 };
result.push(hash[day]);
}
hash[day][{ d: 'day', n: 'night' }[a.scale]] += a.count;
});
return result;
}();
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 合并新对象中的对象属性并插入数组,无需 jquery 和 lodash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41718857/