![](/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.