javascript - 如何使用 for of 和 for in 语句在 Javascript 对象数组中仅获取一个值?
问题描述
这是我的对象数组,我想在其中获得特定值。
{ customerName: "Jay", Purchased: "phone", Price: "€200" },
{ customerName: "Leo", Purchased: "car", Price: "€2000" },
{ customerName: "Luk", Purchased: "Xbox", Price: "€400" },
];
在这个函数中,我将所有值放在一起。但我想要特定的值,以便在控制台中使用 for of 和 for in 语句显示这样的东西。"Dear Jay thank you for purchase of a phone for the price of €200 "
function getValue(){
for(let key of customerData){
for(let value in key){
console.log(key[value]) //I get all values
//console.log(value) // I get all keys
}
}
}
getValue();```
解决方案
通过将数组中的对象位置作为函数的参数传递,您可以获得单个对象键
function getValue(data){
for(let key of Object.values(data)){
console.log(key)
}
}
getValue(a[1]);
// 输出 Leo 汽车 €2000
推荐阅读
- python - Python文件解析,无法在新行中捕获字符串
- android - 在 Firebase 实时数据库上等待的先前任务需要先完成,然后才能启动新任务
- c# - MS Access 中带有日期类型参数的 SQL 语句
- android - Android和Photoshop之间的rgb值不同?
- elasticsearch - 用户 [elastic] 未授权操作 [clustering/cluster]
- python - 20 次掷骰的随机模拟
- python - 与 Django 一起安装的 shell_plus 给出错误 - ImportError: cannot import name 'Type
- javascript - Require.js - “模块名称...尚未加载上下文:”
- mongodb - 如何在 Go 中模拟 MongoDB 时添加克隆和复制功能?
- android - 我的 kivy 应用程序无法在我的手机中运行(只是一个黑色屏幕),但可以在我的计算机和 kivy 启动器中运行