Issues updating object in nested arrays

Hi guys

My app has a state which holds a set of objects in a nested array. The structure of the data looks a little like this:

export const mockData= [
	[
		{
			id: 1,
			name: "Oblivion",
			artist: "Royal Blood",
			album: "Typhons",
			playState: "skipped",
		},
		{
			id: 2,
			name: "Folding Stars",
			artist: "Biffy-Clyro",
			album: "Puzzle",
			playState: "skipped",
		}, 

		// more objects here etc... 

	],
	[
		{
			id: 7,
			name: "Wild Child",
			artist: "The Black Keys",
			album: "Delta Kream",
			playState: "skipped",
		},
		{
			id: 8,
			name: "The Way You Used To Do",
			artist: "Queens Of The Stone Age",
			album: "Like Clockwork",
			playState: "skipped",
		},

		// more objects here etc... 

	],
	[
		{
			id: 13,
			name: "Hyper Music",
			artist: "Muse",
			album: "Origin Of Symmetry (XX Anniversary RemiXX)",
			playState: null,
		},
		{
			id: 14,
			name: "Death Breath",
			artist: "Bring Me The Horizon",
			album: "Suicide Season",
			playState: null,
		},

		// more objects here etc... 

	],
];

I’m trying to use useState to update an individual property of a specific object within one of the arrays. I first tried to map over the existing array but couldn’t work out how to do it due to the array being nested within another array.

So instead, I’ve created a shallow copy of the array and updated the object at a specific index using the following code:

setPlaylist((prev) => {
			const newPlaylist = [...prev];


			newPlaylist[ArrayIndex][ObjectIndex] = {
				id: newPlaylist[ArrayIndex][ObjectIndex].id,
				name: newPlaylist[ArrayIndex][ObjectIndex].name
				artist: newPlaylist[ArrayIndex][ObjectIndex].artist,
				album: newPlaylist[ArrayIndex][ObjectIndex].album,
				playState: "played",
			};


			return newPlaylist;
		});
	};

// The Array and Object Indexes are being pulled in from
// a separate state that acts a counter)

Is there a more efficient way to do this? Is there any way I can use object deconstructing to avoid having to list all the properties and values that aren’t being used?

Any help would be much appreciated!

Yes, you can destructure the object just like you can an array.

newPlaylist[ArrayIndex][ObjectIndex] = {
				...newPlaylist[ArrayIndex][ObjectIndex],
				playState: "played",
			};
1 Like

That’s great thank you; it seems so obvious now!