skip to Main Content

I’m beginner in JS

Can you help me with simple question, pls?

e.g. I have array such as:

const array = [{
    id: 1,
    name: 'Ferrari',
    type: 'F40',
    price: '350 000$',
    country: 'Italy'
}];

How could I copy this array and make changes in copied array?

For example I need such array as:

const copiedArray= [{
        id: 2,
        name: 'Audi',
        type: 'A7',
        price: '100 000$',
        country: 'Germany'
    }];

Should I write some functions for this?

Thanks for your help!

2

Answers


  1. The new way to do it is the structuredClone function.

    let copiedArray = structuredCopy(array);
    copiedArray[0].name = "new-name";
    
    Login or Signup to reply.
  2. You can write a helper function and called it wherever you want

    const originalArray = [{
      id: 1,
      name: 'Ferrari',
      type: 'F40',
      price: '350 000$',
      country: 'Italy'
    }];
    
    
    const newData = {
      id: 2,
      name: 'Audi',
      type: 'A7',
      price: '100 000$',
      country: 'Germany'
    
    }
    
    function updateObjects(originalArray, newData) {
      // Use the map() method to create a new array with updated object data
      const newArray = originalArray.map(obj => Object.assign({}, obj, newData));
    
      // Return the new array
      return newArray;
    }
    
    
    const newArray = updateObjects(originalArray, newData);
    
    console.log(newArray);
    
    //newArray 
    // [ {
    //   country: "Germany",
    //   id: 2,
    //   name: "Audi",
    //   price: "100 000$",
    //   type: "A7"
    // }]
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search