我有一个数组数组。如何将它们转换为组合在一起的对象数组?
var abc = [
['apple', 'fruit'], ['banana', 'fruit'], ['grapes', 'fruit'], ['red', 'color'], ['blue', 'color'], ['black', 'color']
]
abc = abc.map(function(item) {
return {
value: item[0],
color: item[1]
}
})
colors = abc.filter(function(item) {
return item.color === 'color'
})
fruits = abc.filter(function(item) {
return item.color === 'fruit'
})
var result = [{
group: 'color',
value: colors.map(function(item) {
return item.value
})
}, {
group: 'fruit',
value: fruits.map(function(item) {
return item.value
})
}]
console.log(result)
我的预期输出是:
var abc = [
{
group: 'color',
value: ['red', 'blue', 'black']
},
{
group: 'fruit',
value: ['apple', 'banana', 'grapes']
}]
有没有更简单的方法来实现这一目标?
我也可以使用 lodash。请指教。
最佳答案
这是一种使用reduce
和map
的方法。 reduce
通过映射到值数组的 group
执行聚合。 Object.entries()
和 map
将此分组转换为对象数组形式的所需格式。
var abc = [
['apple', 'fruit'],
['banana', 'fruit'],
['grapes', 'fruit'],
['red', 'color'],
['blue', 'color'],
['black', 'color']
];
const result = Object.entries(
abc.reduce((a, e) => {
if (!(e[1] in a)) {
a[e[1]] = [];
}
a[e[1]].push(e[0]);
return a;
}, {})
).map(e => ({group: e[0], value: e[1]}))
;
console.log(result);
关于javascript - 将数组数组转换为组合在一起的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52653431/