如何更改数组内部对象的属性值

时间:2020-06-09 16:43:22

标签: javascript

我正在尝试更改对象的属性值,该对象位于数组内部,而该数组也位于一个对象内部。

我写了下面的代码来解决问题,但是只取最后一个值。

我的代码

var arr = [{
    QUALITYNAME: "Berry Fancy",
    RATES: [{
      "UNIT": "LB",
      "CURRENCY": "USD",
      "VALUE": 6.205240232694746
    }]
  },
  {
    QUALITYNAME: "Berry USDA",
    RATES: [{
      "UNIT": "LB",
      "CURRENCY": "USD",
      "VALUE": 5.622770183585882
    }]
  }
];

var value_a1 = null

for (let i = 0; i < arr.length; i++) {
  var result = arr[i].RATES;
  var QUALITYNAME = arr[i].QUALITYNAME;

  console.log("result", result);
  result.forEach((element, index) => {
    value_a1 = element.VALUE;
    value_a1 = parseFloat(value_a1.toFixed(2))
    console.log('value_a1', value_a1);
  });
}

arr.forEach(function(item, index) {
  arr[index] = {
    QUALITYNAME: QUALITYNAME,
    RATES: {
      "UNIT": "LB",
      "CURRENCY": "USD",
      "VALUE": value_a1
    }
  };
});

console.log(arr);

给我输出为

 result arr = [ { QUALITYNAME: 'Berry USDA',
        RATES: { UNIT: 'LB', CURRENCY: 'USD', VALUE: 5.62 } },
      { QUALITYNAME: 'Berry USDA',
        RATES: { UNIT: 'LB', CURRENCY: 'USD', VALUE: 5.62 } } ]

但是我需要它的第一个值也是出现在以下结果中

 result arr = [ { QUALITYNAME: 'Berry Fancy',
        RATES: { UNIT: 'LB', CURRENCY: 'USD', VALUE: 6.21 } },
      { QUALITYNAME: 'Berry USDA',
        RATES: { UNIT: 'LB', CURRENCY: 'USD', VALUE: 5.62 } } ]

请帮助我纠正此问题,或者给我一些提示,以解决问题。

预先感谢

2 个答案:

答案 0 :(得分:2)

在第一个循环完成后,您正在运行第二个循环,因此变量QUALITYNAMErates_a1具有上次迭代的值。

您可以简单地从数组中提取对象并在第一个循环中对其进行修改。

var arr = [{
    QUALITYNAME: "Berry Fancy",
    RATES: [{
      "UNIT": "LB",
      "CURRENCY": "USD",
      "VALUE": 6.205240232694746
    }]
  },
  {
    QUALITYNAME: "Berry USDA",
    RATES: [{
      "UNIT": "LB",
      "CURRENCY": "USD",
      "VALUE": 5.622770183585882
    }]
  }
];

var value_a1 = null

for (let i = 0; i < arr.length; i++) {
  var result = arr[i].RATES[0];
  if (result) {
    result.VALUE = parseFloat(result.VALUE.toFixed(2));
  }
  arr[i].RATES = result;
}

console.log(arr);

答案 1 :(得分:1)

如果我正确理解,您只是想将所有比率四舍五入到两位小数,则可以使用嵌套循环来实现,例如:

var arr = [{
    QUALITYNAME: "Berry Fancy",
    RATES: [{
      "UNIT": "LB",
      "CURRENCY": "USD",
      "VALUE": 6.205240232694746
    }]
  },
  {
    QUALITYNAME: "Berry USDA",
    RATES: [{
      "UNIT": "LB",
      "CURRENCY": "USD",
      "VALUE": 5.622770183585882
    }]
  }
]

// Loop through each array item
arr.forEach((item) => { 
    // Loop through each rate inside the item
    item.RATES.forEach((rate) => {
        // Round to two decimals
        rate.VALUE = parseFloat(rate.VALUE.toFixed(2))
    });
})