首页 > 解决方案 > 如何减去对象值

问题描述

你能告诉我如何减去对象值吗,假设我有一个对象的项目并且有库存

 let theObj = {
    pants: [
       {
       color: "Pink",
       stock: 80,
       price: 30.99
       } 
           ]
    };

那只是没有很多值和键,那个对象有很多数据呢?

举例说明:如果用户想买裤子,在他/她选择了他/她想要的东西后,该对象将减去用户想要购买的数量,如果其他用户购买该裤子,则减去该对象直到用完为止,我希望这是有道理的

我希望我的问题和插图对你有意义

let theObj = {
    pants: [
       {
       color: "Pink",
       stock: 80,
       price: 30.99
       } 
           ]
    };
    
const theData = theObj["pants"].map(e => e.stock - 1)
console.log(theData)
console.log(theObj) // nothing change when i subtact it 

标签: javascriptarraysobjectif-statementiterator

解决方案


您不能使用 MAP,因为它不会改变任何东西。使用 forEach 或类似的循环

let theObj = {
  pants: [{
    color: "Pink",
    stock: 80,
    price: 30.99
  }]
};

theObj["pants"].forEach(e => e.stock -= 1)
console.log(theObj) 

你也许是这个意思?

let theObj = {
  pants: [{
    color: "Pink",
    stock: 80,
    price: 30.99
  }]
};

const purchase = { pants: { color: "Pink", quantity:2 }} // your user changes this

// this can be in a function

const item = Object.keys(purchase)[0];
theObj[item].forEach((e) => { if (e.color==purchase[item].color) e.stock -= purchase[item].quantity })
console.log(theObj)


推荐阅读