0

I have an object array

const arr =
[
  { id: 1, name : "Joe", age:20, email: "joe@hotmail.com"},
  { id: 2, name : "Mike", age:50, email: "mike@hotmail.com"},
  { id: 3, name : "Joe", age:45, email: "harry@hotmail.com"}
]

How can I create a new array without modifying first one with only one property changed, like this (id is unique):

[
  { id: 1, name : "Joe", age:20, email: "joe@hotmail.com"},
  { id: 2, name : "Mike", age:50, email: "mike@hotmail.com"},
  { id: 3, name : "Harry", age:45, email: "harry@hotmail.com"}
]

Changed last element name property from "Joe" to "Harry"

nawkee
  • 33
  • 6
  • Clone the array and modify it? Or clone the array and objects and modify it? – VLAZ Sep 17 '20 at 16:22
  • Of interest: [What is the most efficient way to deep clone an object in Javascript](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript) – lurker Sep 17 '20 at 16:34

2 Answers2

1

Below I have created a sample snippet which clones the array of objects and modifies only the name of the object where id = 3.

const arr = [{id:1,name:"Joe",age:20,email:"joe@hotmail.com"},{id:2,name:"Mike",age:50,email:"mike@hotmail.com"},{id:3,name:"Joe",age:45,email:"harry@hotmail.com"}]

const cloneAndModify = (data) => {
  return data.map(d => ({
    ...d,
    ...(d.id === 3 && {
      name: "Harry"
    })
  }))
}

console.log("Original Array: ", arr);
console.log("Cloned Array: ", cloneAndModify(arr))
.as-console-wrapper {
  max-height: 100% !important;
}

You can replace d.id === 3 condition as per your actual requirement based on which you want to change the name.

Nithish
  • 5,393
  • 2
  • 9
  • 24
0

You would first need to clone the array either manually or using a library function like lodash._cloneDeep (https://www.npmjs.com/package/lodash.clonedeep).

If you want to do it manually, just loop over each property of the array elements and copy that into a new array.

After that you can change the cloned array however you like and it will not affect the original one.

Dharman
  • 30,962
  • 25
  • 85
  • 135
tyxeron
  • 1
  • 1