如何仅使用for和for in语句在Javascript对象数组中获取一个值?

问题描述 投票:0回答:2

这里是我要获取特定值的对象数组。

  { customerName: "Jay", Purchased: "phone", Price: "€200" },
  { customerName: "Leo", Purchased: "car", Price: "€2000" },
  { customerName: "Luk", Purchased: "Xbox", Price: "€400" },
];

在此函数中,我将所有值汇总在一起。但是我想要特定的值,以便使用for和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
2个回答
0
投票

您不需要为此使用多个for循环。您可以使用一个forEach()循环和forEach()这样执行此操作:


0
投票

您需要传递正在寻找的客户的名称和想要的有关他们的数据。然后您可以使用var customerData = [{ customerName: "Jay", Purchased: "phone", Price: "€200" }, { customerName: "Leo", Purchased: "car", Price: "€2000" }, { customerName: "Luk", Purchased: "Xbox", Price: "€400" }, ]; function getValue() { customerData.forEach(x => { console.log(`Dear ${x.customerName} thank you for purchase of a ${x.Purchased} for the price of ${x.Price}`) }) } getValue();Array.filter()

Array.map()
© www.soinside.com 2019 - 2024. All rights reserved.