Home > Back-end >  How to add 2 new properties to each array item within my object
How to add 2 new properties to each array item within my object

Time:10-30

I am trying to add 2 new properties to each array item within my object before saving it to the state. I need to add Value & Label properties to the Declarations array with the value of the Declarations.countryName. Tried the code below, but not to sure how to achieve this:

  public getProfile() {
    axios
    .post('https://func-portal-dev.azurewebsites.net/api/GetUserProfile',
    {
      "EmailAddress": "[email protected]"
    })
    .then(res => {
      console.log('Profile.data:', res.data);
      this.setState({profile: res.data.map(p => {
        return {
          ...p,
          // New properties I am trying to create
          p.Declarations.Value: p.Declarations.countryName,
          p.Declarations.Label: p.Declarations.countryName,
        }
      })
    })})
    // Error catching
    .catch(error => this.setState({ error, isLoading: false }));
  }

enter image description here

CodePudding user response:

try this

public getProfile() {
        axios
            .post('https://func-portal-dev.azurewebsites.net/api/GetUserProfile',
                {
                    "EmailAddress": "[email protected]"
                })
            .then(res => {
                console.log('Profile.data:', res.data);

                let profileData = {...res.data};
                 profileData.Declarations = res.data.Declarations.map((item)=>{
                     const newDec = {...item}
                     newDec.Value = item.countryName;
                     newDec.Label = item.countryName;
return newDec
                 })

                this.setState(profileData)
                
                })})
            // Error catching
            .catch(error => this.setState({ error, isLoading: false }));
    }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related