我想使用 reduce 函式創建一個客戶的字典,我正在使用 forEach
const customers =
[ { name: 'ZOHAIB', phoneNumber: '0300xxxxx', other: 'anything' }
, { name: 'Zain', phoneNumber: '0321xxxxx', other: 'other things' }
]
let customersDictionary = {};
customers.forEach(customer => {
customersDictionary = {
...customersDictionary,
[ customer.phoneNumber ]: {name: customer.name},
};
我想要相同的輸出,但使用 reduce 方法。
customersDictionary =
{ "0300xxxxx": {"name": "ZOHAIB"}
, "0321xxxxx": {"name": "Zain"}
}
uj5u.com熱心網友回復:
你不需要reduce. 這是一個帶有Array.prototype.map和的單行Object.fromEntries:
Object.fromEntries(customers.map(c => [c.phoneNumber, { name: c.name }]));
使用的變體reduce:
customers.reduce((acc, c) => {
acc[c.phoneNumber] = { name: c.name };
return acc;
}, {});
uj5u.com熱心網友回復:
這應該作業
const customers = [
{ name: "ZOHAIB", phoneNumber: "0300xxxxx", other: "anything" },
{ name: "Zain", phoneNumber: "0321xxxxx", other: "other things" },
];
const customersDictionary = customers.reduce(
(acc, { phoneNumber, name }) => ({
...acc,
[phoneNumber]: { name },
}),
{}
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/386401.html
標籤:javascript 字典
