如何移除对象数组中指定node.id元素并保留原对象结构
问题
我有如下的数组对象结构:
{ "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" } } ] }
我的目标是返回完全相同的结构,但移除数组中node.id等于指定值的元素。当前尝试的代码如下:
// 其中products为上述对象: 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); })
但这段代码返回的是过滤后的数组,丢失了原对象的键名(例如"Custom Mexico"),请问如何实现保留原结构的需求?
解决方案
问题出在Object.keys().map()会返回一个数组,而我们需要的是保留原键名的对象。可以用以下两种方式实现:
方法1:使用reduce构建新对象
通过reduce遍历键名,逐步构建包含过滤后数组的新对象:
const item = "gid://shopify/Product/13s345f67160"; const listCopy = structuredClone(products); const updatedList = Object.keys(listCopy).reduce((acc, key) => { // 过滤当前分组下的元素,排除指定id的项 acc[key] = listCopy[key].filter(obj => obj.node.id !== item); return acc; }, {}); // 初始值为空对象,逐个添加键值对
方法2:直接遍历键名修改副本
如果不需要生成全新对象,可直接在克隆的副本上修改每个分组的数组:
const item = "gid://shopify/Product/13s345f67160"; const updatedList = structuredClone(products); // 遍历每个键名,替换对应数组为过滤后的结果 for (const key of Object.keys(updatedList)) { updatedList[key] = updatedList[key].filter(obj => obj.node.id !== item); }
这两种方法都会完整保留原对象的键名结构,只移除指定node.id的元素。
内容的提问来源于stack exchange,提问作者FabricioG
相关产品推荐
相关产品推荐

