Euridice01
Euridice01

Reputation: 2568

How can I add values from existing object to new object dynamically?

Currently, I have an empty new object and I want to populate values from an existing object to new object because I want to use an object with only limited properties from the existing object (e.g. I only want the four properties instead of eight).

Here's how I am doing the mapping so far:

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

So far, it looks to be storing the values from the existing object to newObject. However, it is only saving the last object values and not the different values from the object. How can I fix this to save all values (not just the last values for every object in the array)?

Upvotes: 0

Views: 55

Answers (2)

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22895

You need to make a copy of that before pushing in array

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

Or Simply create object inside loop. I love to use Array.prototype.forEach and Array.prototype.map

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

Upvotes: 5

Nagnath Prabhu
Nagnath Prabhu

Reputation: 1

Avoid declaring newObject as 'const'. This is an updated code that works for me.

//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={};
}

Upvotes: 0

Related Questions