迭代Object Literal以填充列表



试图弄清楚如何实现这一点:

export const countries = {
AFGHANISTAN: {
countryId: 0,
name: "Afghanistan"
},
ALBANIA: {
countryId: 1,
name: "Albania"
}
}|

然后尝试迭代并返回一些选项:

export const countryOptions = () => {
let countryOptions = [];
for (const [key, value] of Object.entries(countries)) {
const dropdownOption = {
text: {
type: "plain_text",
text: {value.name}
},
value: value.countryId
}
countryOptions.push(dropdownOption);
});
return countryOptions;
}

这不太正确,我不知道如何在这里正确地引用namecountryId

我不认为你可以在这个问题上使用map,因为它不是那种可迭代的,所以这就是我尝试使用Object.entries()的原因。

正如CertainPerformance的评论中所提到的,您有{}的额外功能。

Object.entries(countries).map(([key,value]) => ({
text:{
type: "plain_text",
text: value.name
}
}))

这只是您代码的一个更高级的版本。:(

Object.entries返回一个数组,在该数组上可以使用.map。但在这里,您只关心值,而不关心密钥,所以请使用Object.values

export const countryOptions = () => Object.values(countries)
.map(obj => ({
text: {
type: 'plain_text',
text: obj.name,
},
value: obj.countryId
}));

最新更新