如何动态地将现有对象的值添加到新对象?

时间:2018-04-23 20:00:42

标签: javascript

目前,我有一个空的新对象,我想将现有对象的值填充到新对象,因为我想使用一个只有现有对象的有限属性的对象(例如,我只想要四个属性而不是八个属性)。

以下是我到目前为止的映射方式:

  const newObject: any = {};
  for (let i = 0; i < this.PRODUCT_DATA.length; i++) {

       newObject._productSkuKey = this.PRODUCT_DATA[i]._productSkuKey;
       newObject._storeKey = this.itemPriceForm.get('location').value;
       newObject._price = this.PRODUCT_DATA[i]._price;
       newObject._status = this.PRODUCT_DATA[i]._isActive;
       this.updatedProducts.push(newObject);
    }

到目前为止,它看起来是将现有对象的值存储到newObject。但是,它只保存最后一个对象值,而不保存对象的不同值。如何解决此问题以保存所有值(而不仅仅是数组中每个对象的最后一个值)?

2 个答案:

答案 0 :(得分:4)

在推入数组

之前,你需要复制一份
const newObject: any = {};
for (let i = 0; i < this.PRODUCT_DATA.length; i++) {

   newObject._productSkuKey = this.PRODUCT_DATA[i]._productSkuKey;
   newObject._storeKey = this.itemPriceForm.get('location').value;
   newObject._price = this.PRODUCT_DATA[i]._price;
   newObject._status = this.PRODUCT_DATA[i]._isActive;
   this.updatedProducts.push(Object.assign({}, newObject));
   // Or
   // this.updatedProducts.push({ ...newObjec });
}

或者只需在循环内创建对象。我喜欢使用Array.prototype.forEachArray.prototype.map

this.updatedProducts = this.PRODUCT_DATA.map(({_productSkuKey, _price, _isActive})=> ({
        _productSkuKey,
        _storeKey: this.itemPriceForm.get('location').value,
        _price,
        _status: _isActive
   });

答案 1 :(得分:0)

避免将newObject声明为'const'。这是一个适合我的更新代码。

//avoid using a const, as you cannot override it
  let newObject: any = {};
  for (let i = 0; i < this.PRODUCT_DATA.length; i++) {

   newObject._productSkuKey = this.PRODUCT_DATA[i]._productSkuKey;
   newObject._storeKey = this.itemPriceForm.get('location').value;
   newObject._price = this.PRODUCT_DATA[i]._price;
   newObject._status = this.PRODUCT_DATA[i]._isActive;
   this.updatedProducts.push(newObject);
   //after pushing the object, empty all the current contents
   newObject={};
}