gpt4 book ai didi

javascript - 从嵌套对象的数组中删除元素?

转载 作者:行者123 更新时间:2023-11-28 13:13:17 25 4
gpt4 key购买 nike

我该怎么做?我的店铺是这样的:

{
...,
playlist : [
...,
{
id : 1,
title : "fancy-playlist-title",
songs : [
{ id : 1 },
{ id : 2 },
... and so on
]
}
]
}

我有这个 reducer :

if(action.type === "REMOVE_FROM_PLAYLIST"){
return {
...state,
playlist : [
...state.playlist,
...state.playlist[action.index].songs.splice(0, action.indexSongs),
...state.playlist[action.index].songs.splice(action.indexSongs+1)
]
}
}

更新

每个播放列表可以有无限的歌曲,因为播放列表数组包含很多像这样的播放列表对象

playlist : [
{
id : 1,
title : "title",
songs : []
},{
id : 2,
title : "playlist 2",
songs : []
},
{... and so on}
]

我的完整 reducer 是这样的

export default function(state = {}, action) {

if(action.type === "REMOVE_FROM_PLAYLIST"){

//action.index : current index of playlist
//action.indexSongs : current index of song that I want to delete from current playlist

let playlist = state.playlist[action.index].slice(0, action.index).concat(state.playlist[action.index].slice(action.index + 1));
return {
...state,
playlist : [
...state.playlist,
...playlist.slice(0, action.indexSongs),
...playlist.slice(action.indexSongs + 1)
]
}
}

return state;
}

我的问题是如何删除一个播放列表中的一首歌曲?我正在发送当前播放列表的索引和当前播放列表歌曲的索引。

最佳答案

splice 改变数组状态,这是你不应该做的。

您想要的是sliceconcat的组合:

playlist.slice(0, indexOfSong)  // copy a portion of the array
// from the start to the indexOfSong

.concat( // concatenate it with:

playlist.slice(indexOfSong + 1)
// copy of a portion of the array from
// the index just after indexOfSong
// to the end of the playlist
);

上面的内容可以使用 ES6 Spread 语法编写,如下所示:

[
...playlist.slice(0, indexOfSong)
...playlist.slice(indexOfSong + 1));
]

EDIT, considering your recent question update, your reducer should look like this:

export default function(state = {}, action) {

if(action.type === "REMOVE_FROM_PLAYLIST"){
return {
...state,
playlist : [
...state.playlist,
...playlist[action.index].songs.slice(0, action.indexSongs),
...playlist[action.index].songs.slice(action.indexSongs + 1)
]
}
}
}

关于javascript - 从嵌套对象的数组中删除元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40772587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com