[英]How to map an array of objects in a a new array with new key value
我有一種情況,我有一個這樣的對象數組:
[
{
"name": "Phone call",
"value": "Phone call"
},
{
"name": "SMS",
"value": "SMS"
},
{
"name": "Email",
"value": "Email"
}
]
我必須將上述 OBJ 重新映射到一個包含其翻譯的新 OBJ,這與 React-intl 中的類似: formatMessage(formatMessage(messages.emailOptionPlaceholder)
想法如下:
if (obj.name === 'Email') formatMessage(formatMessage(messages.emailOptionPlaceholder) else obj.name
所以新數組應該包含正確的翻譯,它將填充一個下拉菜單。
到目前為止,我嘗試過這樣但沒有成功:
field.options.map(o => {
return [
o.name === 'Email'
? formatMessage(messages.emailOptionPlaceholder)
: o.name,
o.name === 'Phone call'
? formatMessage(messages.phoneOptionPlaceholder)
: o.name,
o.name === 'SMS'
? formatMessage(messages.smsOptionPlaceholder)
: o.name,
];
});
這將返回 3 個 arrays 而不是一個具有我需要的值的值。
我的目標是為 object 中的 3 個元素創建一個包含formatMessage(...)
output 的數組,作為 output 的示例:
[{
name: Phone call
value: <-- Phone call translation from formatMessage -->
}
{
name: Email
value: <-- Email translation from formatMessage -->
}
{
name: SMS
value: <-- SMS call translation from formatMessage -->
}
]
我從后端獲取那個 OBJ,需要將相應名稱的翻譯放在下拉菜單中,並且想知道什么解決方案可以更好。
Using.map 是一種可能的解決方案,但是您沒有正確使用它。 來自 mdn :
map() 方法創建一個新數組,其中填充了在調用數組中的每個元素上調用提供的 function 的結果。
要修復您的解決方案,您可以使用以下代碼:
field.options.map((o) => {
if (o.name === "Email") {
return { ...o, value: formatMessage(messages.emailOptionPlaceholder) };
} else if (o.name === "Phone call") {
return { ...o, value: formatMessage(messages.phoneOptionPlaceholder) };
} else if (o.name === "SMS") {
return { ...o, value: formatMessage(messages.smsOptionPlaceholder) };
} else {
return o;
}
});
注意.map返回一個新數組,所以需要保存結果。 如果您想直接改變對象,請使用簡單的 forEach,如下所示:
field.options.forEach(o => {
if (o.name === "Email") {
o.value = formatMessage(messages.emailOptionPlaceholder);
} else if (o.name === "Phone call") {
o.value = formatMessage(messages.phoneOptionPlaceholder);
} else if (o.name === "SMS") {
o.value = formatMessage(messages.smsOptionPlaceholder);
}
})
我會這樣做。 (未測試)
const mappings = {
'Email': messages.emailOptionPlaceholder,
'Phone call': messages.phoneOptionPlaceholder,
'SMS': messages.smsOptionPlaceholder
};
const mapped = field.options.map((obj) => {
const key = mappings[obj.name]
if (key) {
return {
...obj,
value: formatMessages(key)
}
} else {
// no mapping for object name.
// do something to handle it or just return obj
return obj
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.