javascript - 在对象数组上跳过地图
问题描述
我不知道为什么我的地图没有解析。它以某种方式跳过了我的地图,尽管countriesAtoH
它向我显示它确实有一个对象数组但是当我尝试映射它时,它就像它没有映射它,因为我不能在地图中放置断点,而地图最终是没有被调用。意思是我的长度为 0options
const countries = {
Afghanistan: {
countryId: 0,
name: "Afghanistan"
},
Albania: {
countryId: 1,
name: "USA"
},
Algeria: {
countryId: 99,
name: "Canada"
}
}
export const countryOptions = () => {
let countriesAtoH = [];
Object.keys(countries).forEach((c) => {
if (countries[c].countryId <= 97) {
countriesAtoH[c] = countries[c];
}
});
const options = countriesAtoH.map(country => {
const c = {
text: {
type: "plain_text",
text: country.name,
},
value: country.countryId
}
return c;
});
return options;
}
解决方案
你有问题countriesAtoH[c] = countries[c]
。
的类型countriesAtoH
是array
索引应该是数字,并且您将c
值(字符串)值分配为countriesAtoH
数组上的索引。
因此,它不起作用。最好设置countriesAtoH = {}
为对象并用于Object.values(countriesAtoH)
获取options
变量。
const countries = {
Afghanistan: {
countryId: 0,
name: "Afghanistan"
},
Albania: {
countryId: 1,
name: "USA"
},
Algeria: {
countryId: 99,
name: "Canada"
}
}
const countryOptions = () => {
let countriesAtoH = {};
Object.keys(countries).forEach((c) => {
if (countries[c].countryId <= 97) {
countriesAtoH[c] = countries[c];
}
});
const options = Object.values(countriesAtoH).map((country) => {
const c = {
text: {
type: "plain_text",
text: country.name,
},
value: country.countryId
}
return c;
});
return options;
}
console.log(countryOptions());
简单地说,您可以使用Array.prototype.filter
andArray.prototype.map
来获取options
.
const countries = {
Afghanistan: {
countryId: 0,
name: "Afghanistan"
},
Albania: {
countryId: 1,
name: "USA"
},
Algeria: {
countryId: 99,
name: "Canada"
}
}
const countryOptions = () => {
const options = Object.values(countries).filter(({ countryId }) => countryId <= 97).map((item) => ({
text: {
type: "plain_text",
text: item.name
},
value: item.countryId
}));
return options;
}
console.log(countryOptions());
推荐阅读
- python - Python链表合并排序不起作用
- c# - 在 DataTemplate 中重用样式
- jquery - AllSelected 时发送值 -1 - Javascript 多选
- android-automotive - Android Automotive OS - 自定义语音命令
- c# - 确定具有云文件路径的 PDF 文件是否受密码保护(以 https:\\ 开头的路径)
- java - 如何使用密码学在 Python 中使用 Kotlin PublicKey 对象加载编码的公钥
- python - 如何用最小二乘法计算“平方和的相对误差”和“近似解的相对误差”?
- excel - 如何使用 Excel 导入表格并邮寄?
- email - 如何使用电子邮件发送雪花云数据平台查询结果?
- c++ - C++ 接受 int 作为字符向量中的元素