mercredi 18 septembre 2019

javascript - map with conditionally altered nested field

Given an array such as:

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

I am trying to write a function which will alter specific instances of '00000' in the nested field 'zip' to the string '12893' and return a new array identical to the initial array except with the corrected values. My attempt at a function so far is:

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

I know this function is altering the values in 'initialArray', which isn't supposed to happen. How can I go about writing my function so that I can effectively use the map function to create a new, corrected array? Thanks.

Aucun commentaire:

Enregistrer un commentaire