javascript - Javascript - 通过键数组对对象数组进行分组
问题描述
我有这个问题,我想将每个包含类型数组的对象数组分组到数组对象中。
开始:
const start = [
{ name: "Banana", type: ['fruit'] },
{ name: 'Apple', type: ['fruit', 'food'] },
{ name: 'Carrot', type: ['vegetable', 'food'] }
]
期望的结果
const desiredResult = {
'fruit':[
{ name: "Banana", type: ['fruit'] },
{ name: 'Apple', type: ['fruit', 'food'] }
],
'food': [
{ name: 'Apple', type: ['fruit', 'food'] },
{ name: 'Carrot', type: ['vegetable', 'food'] }
],
'vegetable':[
{ name: 'Carrot', type: ['vegetable', 'food'] }
]
};
我被困在哪里,不知道现在如何映射该类型数组:D 目前只有 a.type[0],这很糟糕。
const groupedData = start.reduce(function (r, a) {
r[a.type[0]] = r[a.type[0]] || [];
r[a.type[0]].push(a);
return r;
}, {});
解决方案
您需要遍历a.type
.
const groupedData = start.reduce(function(r, a) {
a.type.forEach(type => {
r[type] = r[type] || [];
r[type].push(a);
});
return r;
}, {});
推荐阅读
- hyperledger-fabric - Hyperledger Fabric 2.0 byfn.sh 错误安装链码
- android - 分支仪表板中指定的与清单文件中的深层链接意图不匹配
- svelte - Svelte 商店有条件的自动订阅
- javascript - 在选择时将下拉值从函数传递给 React.useEffect()
- javascript - 重试加载 iframe 直到成功?
- javascript - 有没有办法让 v-on:click 仅显示特定对象的模式?
- r - 尝试在 r 上下载 Github 包时出错
- java - Android 蓝牙 LE 扫描仪仅在某些设备中打开手机位置时进行扫描
- css - 关闭转换,具有 !important 值,在响应时关闭
- postgresql - 在 POSTGRESQL 11.7 上 DROP TABLE 时自动 DROP FUNCTION