![](/img/trans.png)
[英]How to remove a simple specific key value pair from all objects and add to one specific object inside an array
[英]Remove object key and value inside of Array of Objects
我的代碼 =
這是我的示例數據。
const songs = [
{
"title": "Just Once",
"asset_id": "1f7e0fd8-db21-4c28-b9e1-eb0295af198c",
"sort": 1,
"performers": [
{
"last_name": "John",
"first_name": "Doe",
"group": {
"group_id": "1e5f73fa-ffe8-4c70-a83b-84e7bf985b25",
"dept_short_name": "PAO",
"dept_long_name": "Public Affairs Office"
},
"email": "john@doe.com"
}
]
}
]
const newTest= songs.map(( {...song} ) => (
song.performers.map(({...group}) => group_id = group.group_id)
))
結果我得到了這個:
我應該只從組對象中刪除dept_short_name和dept_long_name ,而group_id將保留,歌曲的其余數據應保持不變。
結果應該是這樣:
[
{
"title": "Just Once",
"asset_id": "1f7e0fd8-db21-4c28-b9e1-eb0295af198c",
"sort": 1,
"performers": [
{
"last_name": "John",
"first_name": "Doe",
"group_id":"1e5f73fa-ffe8-4c70-a83b-84e7bf985b25"
"email": "john@doe.com"
}
]
}
]
您需要在兩個地圖中重新創建一個對象。
const songs = [{"title":"Just Once","asset_id":"1f7e0fd8-db21-4c28-b9e1-eb0295af198c","sort":1,"performers":[{"last_name":"John","first_name":"Doe","group":{"group_id":"1e5f73fa-ffe8-4c70-a83b-84e7bf985b25","dept_short_name":"PAO","dept_long_name":"Public Affairs Office"},"email":"john@doe.com"}]}] const updated = songs.map(({ performers, ...song }) => ({ ...song, // recreate song object performers: performers.map(({ group: { group_id }, ...performer }) => ({ ...performer, // recreate performer object group_id })) })) console.log(updated)
{
"title": "Just Once",
"asset_id": "1f7e0fd8-db21-4c28-b9e1-eb0295af198c",
"sort": 1,
"performers": [
{
"last_name": "John",
"first_name": "Doe",
"group": {
"group_id": "1e5f73fa-ffe8-4c70-a83b-84e7bf985b25",
"dept_short_name": "PAO",
"dept_long_name": "Public Affairs Office"
},
"email": "john@doe.com"
}
]
}
]
window.addEventListener('load', function() {
delete songs[0].performers[0].group.dept_short_name;
delete songs[0].performers[0].group.dept_long_name;
console.log(JSON.stringify(songs))
});
這可能會有所幫助。
const songs = [{
title: "Just Once",
asset_id: "1f7e0fd8-db21-4c28-b9e1-eb0295af198c",
sort: 1,
performers: [{
last_name: "John",
first_name: "Doe",
group: {
group_id: "1e5f73fa-ffe8-4c70-a83b-84e7bf985b25",
dept_short_name: "PAO",
dept_long_name: "Public Affairs Office"
},
email: "john@doe.com"
}]
}];
songs.map(({ performers }, ind) => {
performers.map(({ group }, ind) => {
performers[ind].group_id = group.group_id;
});
delete performers[ind].group;
});
console.log(songs);
使用delete關鍵字:delete performerce ["keyname"] 返回布爾值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.