我几乎解决了这个问题,但是我在如何将特定值放入数组上有了一个思路,这种想法是对具有相同id的数组进行“分组”,在这种情况下将其所有值合并为单个属性“字符”属性,这已经完成,我已经设法解决了,现在的问题是我无法获取角色属性的值,我该如何获取呢?我已经尝试了map,但是我得到了一个从索引0到2的角色数组。我也尝试了_.forEach,但使用lodash的结果相同。
var groupArr = [ { id: 'Jesse', role: 'merchant', character: 'Orc', }, { id: 'David', role: 'hero', character: 'Blade Knight', }, { id: 'Jesse', role: 'merchant', character: 'Elf', }, { id: 'Steve', role: 'villain', character: 'Undead OverLord', }, { id: 'Jesse', role: 'merchant', character: 'Wizard', }, ]
var output = _(groupArr).groupBy(a => a.id).map((objs, key) => ({
'id': key,
'role': key,
'character': _.map(objs, 'character')
}))
.value();
console.log(output);
答案 0 :(得分:1)
您可以从组中的第一项担任该角色:
var groupArr = [ { id: 'Jesse', role: 'merchant', character: 'Orc', }, { id: 'David', role: 'hero', character: 'Blade Knight', }, { id: 'Jesse', role: 'merchant', character: 'Elf', }, { id: 'Steve', role: 'villain', character: 'Undead OverLord', }, { id: 'Jesse', role: 'merchant', character: 'Wizard', }, ]
var output = _(groupArr)
.groupBy('id')
.map((objs, key) => ({
'id': key,
'role': _.head(objs).role,
'character': _.map(objs, 'character')
}))
.value();
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
答案 1 :(得分:0)
这是您询问的“ groupBy”,然后让您进行“合并”
var groupArr = [
{ id: 'Jesse', role: 'merchant', character: 'Orc', },
{ id: 'David', role: 'hero', character: 'Blade Knight', },
{ id: 'Jesse', role: 'merchant', character: 'Elf', },
{ id: 'Steve', role: 'villain', character: 'Undead OverLord', },
{ id: 'Jesse', role: 'merchant', character: 'Wizard', }
];
let byId = groupArr.reduce( (acc, i) => {
acc[i.id] = acc[i.id] || [];
acc[i.id].push(i);
return acc;
}, {});
Object.keys(byId).forEach(id => {
let values = byId[id];
//Do the merge
});
也可以那样做
let merged = [... newSet(groupArr.map(e => e.id))]
.map( id => {
let values = groupArr.filter( e => e.id === id );
let merge = {}; //You do
return merge;
});