鉴于以下集合,将这些数据合并为按房间分组并使“名称”成为数组的最佳方法是什么;不包括重复项,并且如果有更多字段,则不希望使用键“name”来使其更具动态性:
var roomAssignments = [{
room: 'Foo',
name: 'Fooname',
other: 'Other'
},{
room: 'Bar',
name: 'Barname',,
other: 'OtherBar'
},{
room: 'Foo',
name: 'Baz',,
other: 'Other'
},{
room: 'Foo',
name: 'Baz',,
other: 'Other'
},{
room: 'Foo',
name: 'Bat',,
other: 'Other'
}];
期望的输出:
[{
room: 'Foo',
name: [ 'Fooname', 'Baz', 'Bat' ],
other: ['Other']
}, {
room: 'Bar',
name: [ 'Barname' ],
other: ['OtherBar']
}]
我目前正在使用lodash并且更喜欢那个或普通的javascript。我想我已经看了太长时间,而且我有大约30个需要组合成数组的键,我正在寻找最有效的方法将所有键动态组合成数组。
答案 0 :(得分:1)
您可以使用函数reduce
和函数includes
来放弃重复值。
var roomAssignments = [{ room: 'Foo', name: 'Fooname', other: 'Other'},{ room: 'Bar', name: 'Barname', other: 'OtherBar'},{ room: 'Foo', name: 'Baz', other: 'Other'},{ room: 'Foo', name: 'Baz', other: 'Other'},{ room: 'Foo', name: 'Bat', other: 'Other'}],
result = Object.values(roomAssignments.reduce(function(a, c) {
if (a[c.room]) {
Object.keys(c).forEach(function(k) {
if (k === 'room') return;
if (a[c.room][k]) {
if (!a[c.room][k].includes(c[k])) a[c.room][k].push(c[k]);
} else a[c.room][k] = [c[k]];
});
} else {
a[c.room] = { room: c.room };
Object.keys(c).forEach(function(k) {
if (k === 'room') return;
a[c.room][k] = [c[k]];
});
}
return a
}, {}));
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)
“高效”是一种主观的。以下代码相当有效,但更重要的是,它看起来更好。
var rooms = {};
roomAssignments.forEach(assignment => {
var title = assignment.room;
// grab existing room from our rooms map
// if it doesn't exist, create it
var room = rooms[title] || (rooms[title] = {room: title});
for(var k in assignment){
// skip the room key (it's our room title)
if(k === 'room') continue;
var value = assignment[k];
// grab the existing field from the room object
// if it doesn't exist, create it
var field = room[k] || (room[k] = []);
// see if the value already exists
// if not, push it
if(field.indexOf(value) === -1) field.push(value);
}
})