1

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!

  • 1
    Does this answer your question? [How do you clone an array of objects in JavaScript?](https://stackoverflow.com/questions/597588/how-do-you-clone-an-array-of-objects-in-javascript) – PM 77-1 Mar 06 '23 at 22:33
  • If I add: const newArray = array.map(a => Object.assign({}, a)); newArray.name = 'BMW' console.log(newArray) I will get: [ { id: 1, name: 'Ferrari', type: 'F40', price: '350 000$', country: 'Italy' }, name: 'BMW' ] How to change name inside the object not to add another one name parameter? – Danny Fenton Mar 06 '23 at 22:49

2 Answers2

1

The new way to do it is the structuredClone function.

let copiedArray = structuredCopy(array);
copiedArray[0].name = "new-name";
Evan
  • 35
  • 4
1

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"
// }]