Javascript 迭代对象文字以填充列表
正在尝试找出如何使其工作:Javascript 迭代对象文字以填充列表,javascript,Javascript,正在尝试找出如何使其工作: export const countries = { AFGHANISTAN: { countryId: 0, name: "Afghanistan" }, ALBANIA: { countryId: 1, name: "Albania" } }| 然后尝试迭代并返回一些选项: export const countryOptions
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;
}
这不太正确,我不知道如何在这里正确引用name
和countryId
我不认为你可以在这上面使用
映射
,因为它不是那样的一个iterable,所以我尝试通过对象.entries()
对象。entries
返回一个数组,可以在该数组上使用.map
。但在这里,您只关心值,而不关心键,因此请使用Object.values
:
export const countryOptions = () => Object.values(countries)
.map(obj => ({
text: {
type: 'plain_text',
text: obj.name,
},
value: obj.countryId
}));
正如CertainPerformance在评论中提到的,您有
{}
的额外费用
Object.entries(countries).map(([key,value]) => ({
text:{
type: "plain_text",
text: value.name
}
}))
这只是您的代码的更高级版本。:)
{value.name}
语法无效。更改为value.name
对我来说是合理的吗?你可以在Object.entries()
或Object.values()
返回的数组上使用map()
。@CertainPerformance为什么你要删除你的答案,我打算接受它,因为我喜欢你允许的方式。再映射一次。我意识到第一部分是错误的(Object.entries返回一个数组,而不是一个泛型iterable),因此我删除了一分钟的答案来修复它,但随后问题被删除,当时我无法取消删除答案。立即取消删除谢谢,我想我应该先尝试一下。