如何减去对象值

时间:2018-11-07 14:13:26

标签: javascript arrays object if-statement iterator

您能告诉我如何减去对象值吗? 假设我有一个物品的对象并且有库存

 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 

3 个答案:

答案 0 :(得分:1)

您无法使用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)

答案 1 :(得分:1)

而不是.map,您应该做.forEach

let theObj = {
        pants: [
           {
           color: "Pink",
           stock: 80,
           price: 30.99
           } 
               ]
        };
        
theObj["pants"].forEach(e => e.stock -= 1)
    
console.log(theObj)

答案 2 :(得分:0)

您可以使用递归函数并将其泛化。遍历所有键并检查值是否为对象,如果object然后调用同一函数(递归),如果值是数组,则迭代该数组并递归调用传递不同对象的同一函数

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

function doOp(keyName, obj) {
  for (let keys in obj) {
    // check if current value is an array
    if (Array.isArray(obj[keys])) {
      obj[keys].forEach(function(item) {
        // call the same function and pass the objecr
        doOp(keyName, item);
      })
    } else if (typeof obj[keys] === 'object' && typeof obj[keys] !== null) {
      doOp(keyName, obj[keys])
    } else if (keys === keyName) {
      obj[keys] = obj[keys] - 1
    }
  }
}

doOp('stock', theObj)
console.log(theObj)
    我期望结果是

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