如何为对象内部的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
相关产品推荐
相关产品推荐

