0

I have an object array

const arr =
[
  { id: 1, name : "Joe", age:20, email: "[email protected]"},
  { id: 2, name : "Mike", age:50, email: "[email protected]"},
  { id: 3, name : "Joe", age:45, email: "[email protected]"}
]

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: "[email protected]"},
  { id: 2, name : "Mike", age:50, email: "[email protected]"},
  { id: 3, name : "Harry", age:45, email: "[email protected]"}
]

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

2

2 Answers 2

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:"[email protected]"},{id:2,name:"Mike",age:50,email:"[email protected]"},{id:3,name:"Joe",age:45,email:"[email protected]"}]

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.