我有一个具有多个属性和值的对象。我如何一次性获取所有内容?
在以下代码中,产品具有多个值。我想获取所有价格,并希望使用java脚本
来总结它们代码如下。
var products = [
{name:"anti-glair", price:100, quantity:200, status:"available"},
{name:"Lens", price:300, quantity:35, status:"Un-available"},
{name:"Optics", price:150, quantity:500, status:"available"}
];
我正在尝试这样
console.log(products.price);
但它显示为未定义。
我也想要所有产品的总和。
答案 0 :(得分:0)
products
指的是一个数组。您可以使用索引0访问该数组中的第一个对象,使用索引1访问第二个对象等。或者您可以使用for
循环,products.forEach
或其他多种方式遍历数组在this question的答案中。
获得对象后,您可以使用已显示的语法访问其属性。
例如:
var products = [
{name:"anti-glair", price:100, quantity:200, status:"available"},
{name:"Lens", price:300, quantity:35, status:"Un-available"},
{name:"Optics", price:150, quantity:500, status:"available"}
];
console.log(products[0].price);

答案 1 :(得分:0)
使用更高阶的功能。要获得一系列价格,
let prices = products.map(x => x.price)
然后总结一下,
let totalCost = prices.reduce((x, y) => x + y)
答案 2 :(得分:0)
尝试这个,这就是你想要的。
var products = [
{name:"anti-glair", price:100, quantity:200, status:"available"},
{name:"Lens", price:300, quantity:35, status:"Un-available"},
{name:"Optics", price:150, quantity:500, status:"available"}
];
var TotalPrice = 0;
var obj = {};
for(var i = 0; i< products.length; i++){
TotalPrice = TotalPrice + products[i].price;
obj[i] = { price : products[i].price};
}
obj.total_price = TotalPrice;
console.log(obj);
答案 3 :(得分:0)
对于迭代并获得总和或价格使用 Array#reduce
方法
var sum = products.reduce(function(a, b) {
// calculate the price and add with total
// multiply with `quantity` property if you want
return a + b.price;
// set initial value as 0
}, 0);
var products = [{
name: "anti-glair",
price: 100,
quantity: 200,
status: "available"
}, {
name: "Lens",
price: 300,
quantity: 35,
status: "Un-available"
}, {
name: "Optics",
price: 150,
quantity: 500,
status: "available"
}];
var sum = products.reduce(function(a, b) {
return a + b.price;
}, 0);
console.log(sum)
答案 4 :(得分:0)
在迭代其余数据之前先获取对象的长度:
var products = [
{name:"anti-glair", price:100, quantity:200, status:"available"},
{name:"Lens", price:300, quantity:35, status:"Un-available"},
{name:"Optics", price:150, quantity:500, status:"available"}
];
var sumPrices = 0;
for(i = 0; i < products.length; i++) {
console.log("Name: " + products[i].name + ", Price: " + products[i].price + ", Quantity: " + products[i].quantity[i] + ", Status: " + products[i].status);
sumPrices = sumPrices + products[i].price;
}
console.log("Total sum of prices: " + sumPrices);