gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:52:41 25 4
gpt4 key购买 nike

这是我的对象数组,我想在其中获取特定值。

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

在这个函数中,我将所有值放在一起。但我想要特定的值,以便使用 for of 和 for in 语句在控制台中显示这样的内容。 “亲爱的 Jay,感谢您以 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();```

最佳答案

为此,您不需要多个 for 循环。您可以使用 forEach() 来完成此操作循环和template literal像:

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();

关于javascript - 如何使用 for of 和 for in 语句仅获取 Javascript 对象数组中的一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61698279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com