![](/img/trans.png)
[英]How to access properties of a JavaScript object using the property values of another object
[英]How to get property values of object using javascript
我有一个具有多个属性和值的对象。 我如何一次获取所有内容?
在下面的代码中,产品具有多个值。 我想获取所有价格,并希望使用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);
但是它显示为未定义。
我也希望所有产品的总和。
products
是指数组。 您可以使用索引0来访问该数组中的第一个对象,使用索引1来访问第二个对象,等等。或者您可以使用for
循环, products.forEach
或该问题的答案中概述的许多其他方式来遍历该数组。 。
获得对象后,就可以使用显示的语法访问其属性。
因此,例如:
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);
使用高阶函数。 要获得一系列价格,
let prices = products.map(x => x.price)
然后总结一下,
let totalCost = prices.reduce((x, y) => x + y)
试试这个,这就是您想要的。
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);
为了迭代并获得总和或价格,请使用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)
在迭代其余数据之前,首先获取对象的长度:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.