首页 > 解决方案 > 如何使用 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();```

标签: javascript

解决方案


通过将数组中的对象位置作为函数的参数传递,您可以获得单个对象键

function getValue(data){
    for(let key of Object.values(data)){
        console.log(key)
    }
}

getValue(a[1]);

// 输出 Leo 汽车 €2000


推荐阅读