【发布时间】:2019-06-16 09:45:59
【问题描述】:
所以我有一个对象数组,我创建了两个字典来映射名称。 我想找到所有具有相同键的对象并将它们合并。还要连接该值。 这是我所做的,但卡住了:
const wordcloudData = {
'pretty cool': [3, 1, ['161', '329']],
'pretty damn': [2, 1, ['111', '131']],
'pretty nice': [1, 1, ['211', '499']],
'great': [4, 1, ['18', '19']],
};
const dict = {
'pretty cool': 1,
'pretty damn': 1,
'pretty nice': 1,
};
const dictNames = {
1: 'nice',
}
const formattedArray = _
.chain(wordcloudData)
.keys()
.map(item => {
const [weight, color, reviews] = wordcloudData[item];
return {
name: dictNames[dict[item]] || item,
weight: weight,
color: color,
reviews: reviews,
}
})
/* Here i'm getting that type of array:
[
{ name: 'nice', weight: 1, color: 1, reviews: [ '211', '499' ] },
{ name: 'nice', weight: 2, color: 1, reviews: [ '111', '131' ] },
{ name: 'nice', weight: 3, color: 1, reviews: [ '161', '329' ] },
{ name: 'great', weight: 4, color: 1, reviews: [ '18', '19' ] }
]
*/
.groupBy('name')
.map(_.spread(_.assign)) // Here i'm trying to get rid of objects with same key, but something goes wrong
.value();
我认为删除重复项时我做错了? 接下来我该怎么做?
为了解释我想要什么,将显示我想要的数组:
对象的初始数组:
{
'pretty cool': [3, 1, ['161', '329']],
'pretty damn': [2, 1, ['111', '131']],
'pretty nice': [1, 1, ['211', '499']],
'great': [4, 1, ['18', '19']],
};
对象的结果数组:
{ name: 'nice', weight: 6, color: 1, reviews: [ '161', '329', '111', '131', '211', '499'] },
{ name: 'great', weight: 4, color: 1, reviews: [ '18', '19' ] }
【问题讨论】:
-
添加示例中 wordcloudData 应创建的最终结果示例?
-
@OriDrori 谢谢,我已经添加了
-
你会接受不使用 lodash 的答案吗?如果在合并时所有项目都具有不同的值,那么颜色的最终值是多少?
-
是的,我会接受不使用 lodash 的答案,映射项目的颜色值将相同,原因之一是我没有在最终结果中指出为数组着色
标签: javascript arrays object ecmascript-6 lodash