Home > Blockchain >  Sum Like Child Variables
Sum Like Child Variables

Time:08-24

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"
  }
};

CodePudding user response:

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)

CodePudding user response:

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)

CodePudding user response:

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