3 回答
TA贡献1821条经验 获得超4个赞
lodash keyBy 可能不是您用例的最佳解决方案,您可以使用array.reduce方法:
action.payload.reduce((accumulator, currentValue) => {
accumulator[currentValue.id] = currentValue.details.colour;
return accumulator;
}, {});
TA贡献1995条经验 获得超2个赞
你可以试试这段代码,Array.reduce 也能做同样的工作。
let arr = [
{
details: {
campus: [
{
address: '115-119...',
campusName: 'blah',
email: 'blah',
},
],
colour: '#640E27',
schoolCode: '8383',
},
enrolled: true,
id: '8383',
},
];
const reducedHash = arr.reduce((acc, data) => {
return { ...acc, ...{ [data.id]: data.details.colour } };
}, {});
TA贡献1796条经验 获得超10个赞
使用.forEach或.reduce
var data = [
{
"details": {
"campus": [
{
"address": "115-119...",
"campusName": "blah",
"email": "blah",
}
],
"colour": "#640E27",
"schoolCode": "8383"
},
"enrolled": true,
"id": "8383"
}
];
var res = {};
data.forEach(({id, details})=>{
res[id] = details.colour
});
console.log(res);
//Reduce
var res2 = data.reduce((acc, {id, details})=>{
return {...acc, ...{[id]:details.colour}}
}, {});
console.log(res2)
添加回答
举报