javascript - modifying nested field based on condition in map

In the scenario of having an array like this:

people = [
    {
        name: 'Bob',
        sex: 'male',
        address:{
          street: 'Elm Street',
          zip: '12893'
        }
    },
    {
        name: 'Susan',
        sex: 'female',
        address:{
          street: 'Hickory Street',
          zip: '00000'
        }
    }
]

I want to create a function that can modify specific instances of '00000' in the nested field 'zip' to '12893' and generate a new array with the corrected values. Here is my current attempt at a function:

function zipFix (initialArray) {
    return initialArray.map(function(person) {
        if(person.address.zip === '00000')
          person.address.zip = "12893"
        return person
    });
}

Although this function is altering the values in 'initialArray', which is not the intended behavior. How can I adjust my function so that I can correctly use the map function to produce a new array with the corrections? Thank you.

Answer №1

When iterating over the values using the map function, it is important to create a copy of each object to avoid mutations. The most convenient way to achieve this is by utilizing the object spread syntax ({...obj}).

By using object spread, all the values (such as name, address, etc.) are spread into a new object, ensuring that any changes made do not affect the original object. However, it is crucial to note that this process is shallow, meaning that although a new object is created, the values inside remain the same. Therefore, in cases where a property like address is also an object, a nested spread of the address value is necessary.

people = [{
    name: 'Bob',
    sex: 'male',
    address: {
      street: 'Elm Street',
      zip: '12893'
    }
  },
  {
    name: 'Susan',
    sex: 'female',
    address: {
      street: 'Hickory Street',
      zip: '00000'
    }
  }
]

function zipFix(initialArray) {
  return initialArray.map(function(person) {
    // Create a new "copy" of the person. Using object spread
    // will create a "shallow" copy, so since address is also an
    // object it will have to be spread (same for other objects that might
    // be mutated).
    const newValue = { ...person, address: { ...person.address }}

    if (newValue.address.zip === '00000') {
      newValue.address.zip = "12893";
    }

    return newValue
  });
}

console.log(zipFix(people))
console.log(people) // unchanged

Answer №2

Make sure to also retrieve values from the callback function and create a duplicate of the element before assigning to prevent any changes

const people = [{name: 'Bob',sex: 'male',address:{street: 'Elm Street',zip: '12893'}},{name: 'Susan',sex: 'female',address:{street: 'Hickory Street',zip: '00000'}}]

function zipFix (initialArray) {
    return initialArray.map(function(person) {
      let newObj = JSON.parse(JSON.stringify(person))
        if(newObj.address.zip === '00000')
           newObj.address.zip ="12893"
      return newObj
    });
}

console.log(zipFix(people))

Answer №3

individuals = [
            {
              person: 'Alex',
              gender: 'male',
              location: {
                street: 'Cedar Avenue',
                zip: '78654'
              }
            },
            {
              person: 'Emily',
              gender: 'female',
              location: {
                street: 'Oak Street',
                zip: '00000'
              }
            }
          ]
          
          function zipCorrection (initialList) {
            return (initialList.map(({location, ...ind}) => (
              location.zip !== '00000' ? { ...ind, location } : {
                ...ind,
                location: {
                  ...location,
                  zip: '78654'
                }
              }
            )));
          }
          
          console.log(zipCorrection(individuals));

Answer №4

Below is an example of how you can manipulate an array of objects in JavaScript:

const people = [{name: 'Bob',sex: 'male',address: {street: 'Elm Street',zip: '12893'}},{name: 'Susan',sex: 'female',address: {street: 'Hickory Street',zip: '00000'}}]
const zipFix = people.map(({address, ...p}) => ({
  ...p,
  address: {
    ...address,
    zip: address.zip === '00000' ? '12893' : address.zip
  }
}))

console.log(zipFix)

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

How can you refresh the source element?

Is there a way to make the browser reload a single element on the page (such as 'src' or 'div')? I have tried using this code: $("div#imgAppendHere").html("<img id=\"img\" src=\"/photos/" + recipe.id + ".png\" he ...

Utilizing Twitter API authentication to prevent hitting rate limits

Currently, I am implementing the Twitter API to showcase the most recent tweets from 4 distinct users on my webpage. It seems that once a certain number of calls are made, an error message appears stating "NetworkError: 400 Bad Request" and prevents the tw ...

Guide to smoothly transition the highlighted <tr> element to the top of the scroll bar

Is there a way to utilize jQuery for animating a selected row to the top of a div with a specific scrollbar style? #sc { border:1px solid black; width:450px; height:80px; overflow:scroll; } <div id="sc"> <table id=&quo ...

Retrieve the binary file data that was sent via Postman using Node.js/Express.js

I am currently testing file uploading in my backend system. I am using Postman to send binary data as a file in the request body, and now I need to extract this data from the POST request. req.body The above code snippet returns a binary buffer that look ...

Issue with Bootstrap Scrollspy: Scrollspy function not functioning as expected

I need help with creating a one-page website where the navbar links change based on the section of the page you are on. I tried implementing it using HTML, but it didn't work out as expected. The code I used was within the container holding different ...

Verilog not updating array assignments

The code snippet below demonstrates my current issue: reg [7:0]data[0:7]; always @(posedge clk) begin data[var1]<=var2; $write("%d:%d:%d", var1, var2, data[var1]); After running this code, I noticed that '3:100:x' is printed instead ...

Submitting a POST request to paginate and sort the results

Currently, I have a system in place where a GET request is used to query the database and display the results. While this method works well, I am looking to transition it into a POST request. This would allow for a more flexible approach by handling JSON b ...

What is the purpose of including the return keyword in this function to ensure the promise functions properly?

Code: script1.js: function retrieveData(fetch) { fetch('some API').then(res => res.json()).then(data => { return { count: data.count, results: data.results } }) } module.exports = retrieveData; script2: const ...

Use Vue JS to send a GET request to the server with custom header settings

When creating a Vue.js component, I want to send a GET request to a server with specific headers. How can I achieve this? Using cURL: -X GET "http://134.140.154.121:7075/rest/api/Time" -H "accept: application/json" -H "Authorization: Bearer eyJhbGciOiJSUz ...

Place the div absolutely on top of the Flash content

Can a <div /> be absolutely positioned over a Flash banner without including wmode="transparent" in the banner? I am trying to display a lightbox above my ads, but I cannot make changes to the banners since they are provided by a third party. Edit: ...

Displaying MySQL data in a table using PHP and MySQL

I have a query function (found in the code snippet below) that I utilize to fetch data from the database. I am seeking advice on how to iterate through and output -ALL- the results into a table format, similar to the example below: This is how I attempted ...

Retrieving and transforming data from a JSON format using Regular Expressions

Hello there, I have a task that requires extracting data from the token_dict object received through the api and converting it. Here's an example: "token_dict": { "0x13a637026df26f846d55acc52775377717345c06": { "chain&qu ...

Nodejs application crashes due to buffer creation issues

router.post('/image', multipartMiddleware , function(req, res) { var file_name = req.body.name; var data = req.body.data; var stream = fs.createReadStream(data); //issue arises here return s3fsImpl.writeFile(file_name , stream).t ...

Exploring nested JSON information through jQuery's AJAX call

I am encountering an issue with accessing JSON data using a jQuery AJAX request in JavaScript. I keep receiving a 'Cannot read property [0] of undefined' error in the console of Google Chrome. Despite trying different approaches, such as referrin ...

Smart method for organizing browsing history

I'm currently working on enhancing the navigation in an AJAX application. Here is my current approach: Whenever a user clicks on an AJAX link, the corresponding call is made and the hash is updated. Upon loading a new page, I verify if the hash exis ...

Order a list based on a specific subsequence

Hey there! I have a collection of file names: "1_EX-P1-H2.3000" "10_EX-P1-H2.3002" "100_EX-P1-H2.3074" "1004_EX-P1-H2.4059" "1006_EX-P1-H2.4070" "2_EX-P1-H2.3000" "3_EX-P1-H2.3000&q ...

The Material UI Elements are not displaying properly as expected. Instead of seeing the MUI elements, a tan box is appearing. What steps can I take to resolve this

I'm currently using Material UI to build a basic header, footer, and profile page. However, whenever I attempt to display any type of element (such as Menu, Appbar, Toolbar, IconButton, Tab, Tabs, etc.), the page only shows a tan box instead of the a ...

Trouble with closing windows in the in-app browser on Android devices

Is there a method to successfully close the in-app browser? Despite window.close working on iOS devices, it is not effective on Android. I have experimented with alternatives like window.top.close and window.open("", "_self") window.close, but none have ...

Issue with VueJS v-for when using dynamic components causing unexpected behavior

Within one of my components, the syntax I am using is as follows: <event-item v-for='(event, index) in events' :is='eventComponent(event)' :key="'event-' + index" :event='event&apos ...

What is the proper way to execute a JavaScript function within a JavaScript file from an HTML file?

I have the following content in an HTML file: <!DOCTYPE html> <!-- --> <html> <head> <script src="java_script.js"></script> <link rel="stylesheet" type="text/css" href="carousel.css"> & ...