You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为对象内部的Declarations数组每一项添加Value、Label两个新属性

存在的问题

  • 语法错误:JS对象字面量中不能直接用p.Declarations.Value作为键名,不符合对象属性定义规则
  • 逻辑错误:Declarations是数组类型,需要遍历它的每一项添加属性,不能直接给数组本身加属性

修正后代码

如果res.data是profile对象数组,用如下写法:

public getProfile() {
    axios
    .post('https://func-portal-dev.azurewebsites.net/api/GetUserProfile',
    {
      "EmailAddress": "benn.king@erfdfd.co.uk"
    })
    .then(res => {
      console.log('Profile.data:', res.data);
      this.setState({
        profile: res.data.map(p => ({
          ...p,
          Declarations: p.Declarations.map(dec => ({
            ...dec,
            Value: dec.countryName,
            Label: dec.countryName
          }))
        }))
      })
    })
    .catch(error => this.setState({ error, isLoading: false }));
}

如果接口返回的res.data是单个profile对象而非数组,去掉外层map即可:

public getProfile() {
    axios
    .post('https://func-portal-dev.azurewebsites.net/api/GetUserProfile',
    {
      "EmailAddress": "benn.king@erfdfd.co.uk"
    })
    .then(res => {
      const profileData = res.data
      console.log('Profile.data:', profileData);
      this.setState({
        profile: {
          ...profileData,
          Declarations: profileData.Declarations.map(dec => ({
            ...dec,
            Value: dec.countryName,
            Label: dec.countryName
          }))
        }
      })
    })
    .catch(error => this.setState({ error, isLoading: false }));
}

内容的提问来源于stack exchange,提问作者BennKingy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 06:06:01