3 回答

TA貢獻1851條經驗 獲得超4個贊
您只需要將動態(tài)密鑰名稱括在方括號中,如下所示:[]
[e.name] : {id: e.id, surname: e.surname }
var arr1 = [ {id: 1, name: 'John', surname: 'Smith'}, {id: 2, name: 'Peter', surname: 'Black'} ];
let arr2 = arr1.map( e => ({ [e.name] : {id: e.id, surname: e.surname} }));
console.log(arr2)
.as-console-wrapper { max-height: 100% !important; top: 0; }

TA貢獻1845條經驗 獲得超8個贊
你可以這樣做;你太近了,只是你忘記了使用綁定鑰匙[obj.name]
let data = [{ id: 1, name: 'John', surname: 'Smith' }, { id: 2, name: 'Peter',surname: 'Black'}]
let finalResult =data.map(obj => ({ [obj.name]: { id: obj.id, surname: obj.surname } }))
console.log(finalResult)

TA貢獻1834條經驗 獲得超8個贊
如果要使用表達式作為鍵,請將其括在方括號中:
let arr2 = arr1.map(e => ({[e.name]: {id: e.id, surname: e.surname}}));
添加回答
舉報