I have the following object of arrays:
{
"Custom Mexico": [
{
"cursor": "eyJsYXNasdf0LCJsYXN0X3ZhbHVlIjoiQWd1YXNjYWxpZW50ZXMgTGljZW5zZSBQbGF0ZSBIYXQifQ==",
"node": {
"id": "gid://shopify/Product/993sasd5454",
"title": "Aguascalientes License Plate Hat"
}
},
{
"cursor": "eyJsYXN0X2lkIasdfYWx1ZSI6IkJhamEgQ2FsaWZvcm5pYSBMaWNlbnNlIFBsYXRlIEhhdCJ9",
"node": {
"id": "gid://shopify/Product/18asdf9144",
"title": "Baja California License Plate Hat"
}
},
{
"cursor": "eyJsYXN0X2asdf3MTYwLCJsYXN0X3ZhbHVlIjoiQmFqYSBDYWxpZm9ybmlhIFN1ciBMaWNlbnNlIFBsYXRlIEhhdCJ9",
"node": {
"id": "gid://shopify/Product/13asdf67160",
"title": "Baja California Sur License Plate Hat"
}
}
],
"Mexico Stuff": [
{
"cursor": "eyJsYXN0asdfjQxNTExNTEyLCJsYXN0X3ZhbHVlIjoiMCJ9",
"node": {
"id": "gid://shopify/Product/73sdf11512",
"title": "Tamaulipas Metal License Plate"
}
},
{
"cursor": "eyJsYXN0X2lkIjasdfNzQ0LCJsYXN0X3ZhbHVlIjoiMCJ9",
"node": {
"id": "gid://shopify/Product/736asdf78744",
"title": "Hidalgo Metal License Plate"
}
},
{
"cursor": "eyJsYXNasdfA4LCJsYXN0X3ZhbHVlIjoiMCJ9",
"node": {
"id": "gid://shopify/Product/736asdf08",
"title": "Guanajuato Metal License Plate"
}
}
]
}
My goal is to return the exact same structure but removing an item if it’s in the array:
// where products is the object above:
const item = "gid://shopify/Product/13s345f67160";
const listCopy = structuredClone(products);
const updatedList = Object.keys(listCopy).map(elGroup => {
return listCopy[elGroup].filter(obj => obj.node.id != item);
})
This returns the array but omits the name of the Object in example "Custom Mexico".
How can I accomplish this?
2
Answers
You could directly mutate the copy and use that afterward.
Alternatively, filter the entries and use
Object.fromEntries
to build the object again. There is no need to make a copy withstructuredClone
in this case.the gist
load in the object you want to update,
loop top level arrays,
look for entry where title matches,
filter that item out.
disclaimer untested.