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

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

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

in this function I get all values together. But I want specific value in order to show smth like this in console using for of and for in statements. "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();```
评论
莫小言
莫小言

You need to pass the name of the customer you're looking for and the data you want about them. Then you can use Array.filter() and Array.map()

let customerData = [{
    customerName: "Jay",
    Purchased: "phone",
    Price: "€200"
  },
  {
    customerName: "Leo",
    Purchased: "car",
    Price: "€2000"
  },
  {
    customerName: "Luk",
    Purchased: "Xbox",
    Price: "€400"
  },
]

function getValue(name, otherKey) {
  return customerData.filter(obj => obj.customerName === name).map(obj => obj[otherKey])[0]
}

console.log(getValue("Jay", "Purchased"))
console.log(getValue("Luk", "Price"))
点赞
评论
景长星
景长星

You don't need multiple for loop for this. You can do this using one forEach() loop and template literal like:

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();
点赞
评论