简体   繁体   English

javascript - map 有条件更改的嵌套字段

[英]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.我正在尝试编写一个 function ,它将嵌套字段“zip”中“00000”的特定实例更改为字符串“12893”,并返回一个与初始数组相同新数组,除了更正的值。 My attempt at a function so far is:到目前为止,我对 function 的尝试是:

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.我知道这个 function 正在改变“initialArray”中的值,这是不应该发生的。 How can I go about writing my function so that I can effectively use the map function to create a new, corrected array? How can I go about writing my function so that I can effectively use the map function to create a new, corrected array? Thanks.谢谢。

While map -ing over the values, you will need to create a copy of each object.map覆盖这些值时,您将需要创建每个 object 的副本。 The easiest way to do so is with the object spread syntax ( {...obj} ).最简单的方法是使用object 扩展语法( {...obj} )。

This will "spread" all the values ( name , adress , etc) into a new object.这会将所有值( nameadress等)“传播”到新的 object 中。 So any changes won't mutate it.所以任何改变都不会改变它。 However, it's "shallow" meaning it will be a new object but its values are the same.但是,它是“浅”的,这意味着它将是一个新的 object,但其是相同的。 So since address is also an object we need to copy that as well, hence the reason for the nested spread of the address value as well.所以由于address也是一个 object 我们也需要复制它,因此address值的嵌套传播也是如此。

 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

You need to return values from callback function too, also make a copy of element before assigning to avoid mutability您还需要从回调 function 返回值,还要在分配之前复制元素以避免可变性

 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))

 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(({address, ...p}) => ( address.zip?== '00000'. {..,p: address }. {..,p: address. {..,address: zip; '12893' } } ))). } console;log(zipFix(people));

You can do:你可以做:

 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM