React add property to immutable object

12,320

Solution 1

You are not storing returned value of map to members variable

getInitialState = () => {
        let members = this.props.members.map((member) => {
            return {
                ...member,
                label: (member.firstName + " " + member.lastName)
            }
        });
        console.log(members); //"label" is not a property of objects

        return {title: "", description: "", responsible: [], typeOf: null, 
                members: members};
    };

Solution 2

The array prototype .map() does not mutate the original array, but returns a new array.

Share:
12,320

Related videos on Youtube

Nocebo
Author by

Nocebo

I'm currently studying business information technology at the university of applied sciences in Konstanz, Germany.

Updated on June 04, 2022

Comments

  • Nocebo
    Nocebo almost 2 years

    I'm trying to add a new property to objects within an array. My idea was to do something like this:

    class Foo extends Component {
        constructor(props) {
            super(props);
    
            this.state = this.getInitialState();
            console.log(this.state); //Property "label" is missing in "members" array
        }
    
        /**
         * Get initial state
         * @returns {{title, description}}
         */
        getInitialState = () => {
            let members = this.props.members.slice();
            members.map((member) => {
                return {
                    ...member,
                    label: (member.firstName + " " + member.lastName)
                }
            });
            console.log(members); //"label" is not a property of objects
    
            return {title: "", description: "", responsible: [], typeOf: null, 
                    members: members};
        };
    
        render () {
             return (<div/>)
        }
    }
    

    I want members to stay/remain immutable, yet adding another property to every object within this array. What am I doing wrong here? Thanks!

  • Nocebo
    Nocebo almost 7 years
    I will ;) Have to wait for 5 min
  • philraj
    philraj almost 7 years
    @Nocebo added an edit to the answer to show that since Array#map already returns a new array, you don't have to use this.props.members.slice().
  • David Fischer
    David Fischer about 3 years
    you create a new object instead of the original. you might loose closures and other binding to the original object.