NinjaCoder
NinjaCoder

Reputation: 58

Sum Like Child Variables

How would I sum the qty variable in each parent variable without doing (flower.blueyellow.qty + flower.redyellow.qty) in the following code:

var flower = {
 blueyellow: { 
    color : "linear-gradient(to right, blue, yellow)",
    src : "https://cdn.pixabay.com/photo/2022/07/22/15/11/woman-7338352_1280.jpg",
    price : 30,
    qty : 0,
    size : "small"
  },
 redyellow: { 
    color : "red, yellow",
    src : "https://cdn.pixabay.com/photo/2022/05/22/16/50/outdoors-7213961_1280.jpg",
    price : 25,
    qty : 0,
    size : "large"
  }
};

Upvotes: 1

Views: 51

Answers (3)

kevin
kevin

Reputation: 1112

var flower = {
 blueyellow: { 
    color : "linear-gradient(to right, blue, yellow)",
    src : "https://cdn.pixabay.com/photo/2022/07/22/15/11/woman-7338352_1280.jpg",
    price : 30,
    qty : 0,
    size : "small"
  },
 redyellow: { 
    color : "red, yellow",
    src : "https://cdn.pixabay.com/photo/2022/05/22/16/50/outdoors-7213961_1280.jpg",
    price : 25,
    qty : 0,
    size : "large"
  }
};

const sum = Object.values(flower).reduce((acc,current) => {
    return acc + current.qty
},0)

console.log(sum)

Upvotes: 1

Nathace
Nathace

Reputation: 486

let sum = 0
for (let [key,value] of Object.entries(flower)) {
  sum += value.qty
}

Upvotes: 0

Spectric
Spectric

Reputation: 31992

Get the property values of the object with Object.values, then reduce over the array and sum the qty property:

const flower={blueyellow:{color:"linear-gradient(to right, blue, yellow)",src:"https://cdn.pixabay.com/photo/2022/07/22/15/11/woman-7338352_1280.jpg",price:30,qty:0,size:"small"},redyellow:{color:"red, yellow",src:"https://cdn.pixabay.com/photo/2022/05/22/16/50/outdoors-7213961_1280.jpg",price:25,qty:10,size:"large"}};

const sum = Object.values(flower).reduce((a, {qty}) => a += qty, 0)
console.log(sum)

Upvotes: 3

Related Questions