Generate a fresh array of objects containing a distinct attribute not found in the original one

I am working with an object array

const arr =
[
  { id: 1, name : "Joe", age:20, email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bed4d1dbfed6d1cad3dfd7d290ddd1d3">[email protected]</a>"},
  { id: 2, name : "Mike", age:50, email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="325f5b5957725a5d465f535b5e1c515d5f">[email protected]</a>"},
  { id: 3, name : "Joe", age:45, email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3b535a4949427b53544f565a525715585456">[email protected]</a>"}
]

Is there a way to create a new array while keeping the first one intact but changing only one property, like this (id must remain unique):

[
  { id: 1, name : "Joe", age:20, email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f55505a7f57504b525e5653115c5052">[email protected]</a>"},
  { id: 2, name : "Mike", age:50, email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="690400020c2901061d04080005470a0604">[email protected]</a>"},
  { id: 3, name : "Harry", age:45, email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cda5acbfbfb48da5a2b9a0aca4a1e3aea2a0">[email protected]</a>"}
]

In the above example, I changed the name property of the last element from "Joe" to "Harry"

Answer №1

Here is a code snippet that demonstrates how to clone an array of objects and only modify the name of the object with an id of 3.

const arr = [{id:1,name:"Joe",age:20,email:"example1@email.com"},{id:2,name:"Mike",age:50,email:"example2@email.com"},{id:3,name:"Joe",age:45,email:"example3@email.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 customize the d.id === 3 condition based on your specific requirements for updating the name.

Answer №2

To duplicate the array, you can either manually recreate it or use a utility function such as lodash._cloneDeep (https://www.npmjs.com/package/lodash.clonedeep).

If you opt for manual duplication, simply iterate through each element of the array and copy it into a new array.

Once the duplication is complete, feel free to modify the cloned array without impacting the original one.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Meteor server has the capability to automatically restart when faced with slow requests

I have a Meteor application that is facing issues with hanging calls. The problem arises when processing a large number of items in a loop and performing upserts on the server-side Mongo database, which I suspect is being done asynchronously. I am aware th ...

How can I combine multiple strings to a single variable in Java?

My goal is to create a variable called Line with the values "hey", "you", and "Mom". Later, I want to be able to retrieve specific strings from this variable by calling Line 0 to get "hey". Currently, my approach looks like this: String[] history = new S ...

Run JavaScript code that has been fetched using AJAX

I am currently working on dynamically updating a javascript array based on data returned from an ajax call. Here is the code I have been using: function makeAjaxCall(data) { xmlhttp = new XMLHttpRequest(); xmlhttp.open("POST", "ShowBusiness", fals ...

Unlocking the Magic of JSONP: A Comprehensive Guide

Currently attempting to utilize JSONP in order to work around Cross Domain challenges. I referenced this solution: Basic example of using .ajax() with JSONP? $.getJSON("http://example.com/something.json?callback=?", function(result){ //response data a ...

Firebase is currently experiencing issues with authenticating and removing onDisconnect() functionality

I am encountering issues with implementing onDisconnect().remove() in conjunction with authentication/security rules. Here is what I have set up: Initially, the user is logged in using auth(): var rootRef = new Firebase(FIREBASE_URL + 'sites/' ...

Retrieve the student ID from the URL parameters and display all records with the matching ID

I am trying to display all rows with the same id using $_GET['student_id'], but I am encountering an error with Datatables. Here is my code. When I get the id from the URL, for example: example.com/example.php?=2222 All rows with the id 2222 wil ...

Advantages of passing individual variables instead of the entire object from HTML to JavaScript in AngularJS

When it comes to passing the iterating object from HTML to Javascript, there are two approaches that can be taken. The first approach involves passing the iterating object as a whole, while the second approach only passes the required properties of the obj ...

Upon submission of user-entered data, save it in an HTML table by creating an array variable for each column of the table

There is an HTML table containing multiple rows where users can input details such as Sprint, Role, Project, and Comments. The remaining fields, SID and Project Code, are fetched from the backend when the user clicks on the getDetails button. Users have th ...

Stop automatic selection of the last value in ng-options using AngularJS

I'm facing an issue related to AngularJS. The problem I'm encountering is that... In my code, there are two select elements. Whenever I choose an option from the first select, an Ajax call is made using ng-change to populate the second select ba ...

Designing multiple button actions in v-card-actions in Vuetify: A step-by-step guide

Trying to streamline the v-card-actions on my Vuetify v-cards. My aim is to center the test button within the v-card and position it above the like and share "footer" buttons. I want the like and share footer buttons to be at the bottom of the v-card with ...

Obtaining data from HTML input in Flask while dynamically altering the website's URL

I have a text box in my HTML code and I am trying to figure out how to retrieve the data that is entered into that box when a button is clicked. I have experience getting data from a form using the code snippet below: ex = request.form['example' ...

Having trouble getting my javascript integration to work in a Django template - any ideas on what could be causing

As a newcomer to Django, I'm working on creating a small webpage that displays a chart using Chart.js. My goal is to load the JavaScript file statically. To achieve this, I have set up a basic HTML file named data_table.html and included a "static" fo ...

What is the best way to transfer information from a List<Object> to a String array in an Android application?

This is the specific item I plan to add to the array. All the necessary getters and setters have been defined. public class Task { private int id; private String title; private String description; public Task(){} public Task(String title, String descri ...

Error message encountered when attempting to export functions in Reactjs, resulting in an undefined function error in the context of Reactjs

As I work on creating an adaptive menu using Reactjs and Material UI, I have managed to complete everything. However, I encountered an issue when trying to import a const defined in a different file as the functions are not functioning as expected. The fu ...

Swapping out a character on a webpage using jQuery

Can someone help me remove the colon from this code snippet on my webpage? <h1><b>Headline:</b> something</h1> I'm looking for a simple solution using jQuery, as I am a beginner in JavaScript. Please include the complete code ...

What is causing these TypeScript type assertions to go unnoticed?

While reviewing type assertions, I noticed something interesting about the last three variable assignments - they don't produce errors. It's perplexing because I thought I was trying to change 'helo' into 'hello', which should ...

Developing a dynamic object in Typescript to structure and optimize API responses

Currently Working Explanation: This is similar to the data array received from the API response responseBarDataStacked = [ { sku: "Data 1", month: "Jun", value: 20 }, { sku: "Data 2", month: "Jun", value: 25 ...

How can a new <li> element be created without being influenced by certain CSS styles?

I am attempting to enhance my menubar by adding a signup/login item aligned on the right without affecting the other center-aligned items. Essentially, I have an entry named "Login/Sign Up" that should maintain its own unique style while seamlessly blendin ...

Trouble with ScrollView not scrolling on Nativescript-Vue

I am facing an issue with a scrollable view in my project. I have a list of items that should be scrollable, but for some reason it is not scrolling as expected. The structure involves a vertical stack layout wrapped in a scrollview, and inside the stackla ...

Tips for modifying JSON response using a function

When I call the function buildFileTree, I store its response in a constant variable called data. const data = this.buildFileTree(dataObject, 0); The value of dataObject is: const dataObject = JSON.parse(TREE_DATA); And the content of TREE_DATA is: cons ...