我試圖從嵌套在我的電影物件中的陣列中洗掉一個物件,然后將其復制到一個新變數中。所以我的原始物件是這樣的:
{
"id": 1,
"title": "Avatar",
"movieLength": 162,
"releaseDate": "2009-12-18",
"trailerUrl": "https://www.youtube.com/watch?v=5PSNL1qE6VY",
"genre": {
"id": 1,
"genre": "Action"
},
"rating": {
"id": 3,
"rating": "PG-13"
},
"director": {
"id": 1,
"lastName": "Cameron",
"firstName": "James"
},
"actors": [
{
"id": 2,
"lastName": "Worthington",
"firstName": "Sam"
},
{
"id": 3,
"lastName": "Weaver",
"firstName": "Sigourney"
},
{
"id": 4,
"lastName": "Saldana",
"firstName": "Zoe"
}
],
"comments": []
}
而我現在正在做的是
const updatedMovie = const updatedMovie = movie.actors.filter((actor) => actor.id !== id);
但如您所知,這只回傳我過濾的演員陣列。我想用新過濾的 actor 復制整個物件,這樣物件就會像這樣(洗掉 actor id 3):
{
"id": 1,
"title": "Avatar",
"movieLength": 162,
"releaseDate": "2009-12-18",
"trailerUrl": "https://www.youtube.com/watch?v=5PSNL1qE6VY",
"genre": {
"id": 1,
"genre": "Action"
},
"rating": {
"id": 3,
"rating": "PG-13"
},
"director": {
"id": 1,
"lastName": "Cameron",
"firstName": "James"
},
"actors": [
{
"id": 2,
"lastName": "Worthington",
"firstName": "Sam"
},
{
"id": 4,
"lastName": "Saldana",
"firstName": "Zoe"
}
],
"comments": []
}
我試過四處閱讀,但我沒有找到任何與我一起作業的解決方案的運氣,所以如果有人能幫助或指出我正確的方向,那就太好了!
uj5u.com熱心網友回復:
如果你想變異現有物件,只是其中的結果分配.filter給.actors屬性。
movie.actors = movie.actors.filter((actor) => actor.id !== id);
console.log(movie);
如果要保持現有物件不變,請在過濾時將其余屬性分散到新物件中。
const updatedMovie = {
...movie,
actors: movie.actors.filter((actor) => actor.id !== id)
};
console.log(updatedMovie);
uj5u.com熱心網友回復:
const movies = {
"id": 1,
"title": "Avatar",
"movieLength": 162,
"releaseDate": "2009-12-18",
"trailerUrl": "https://www.youtube.com/watch?v=5PSNL1qE6VY",
"genre": {
"id": 1,
"genre": "Action"
},
"rating": {
"id": 3,
"rating": "PG-13"
},
"director": {
"id": 1,
"lastName": "Cameron",
"firstName": "James"
},
"actors": [
{
"id": 2,
"lastName": "Worthington",
"firstName": "Sam"
},
{
"id": 3,
"lastName": "Weaver",
"firstName": "Sigourney"
},
{
"id": 4,
"lastName": "Saldana",
"firstName": "Zoe"
}
],
"comments": []
}
const id = 3; // or any other id you want
const actors = movies.actors.filter(actor => actor.id != id)
const newMovies = Object.assign({}, movies , { actors })
console.log(newMovies)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/377984.html
上一篇:為什么我的陣列只列印第一個元素?
