按键值从Javascript中的嵌套数组对象中删除项

按键值从Javascript中的嵌套数组对象中删除项,javascript,javascript-objects,Javascript,Javascript Objects,我有这样的目标: { "id": 1, "name": "first", "sections": [ { "id": 1, "title": "First section", "contents": [ { "id": "123", "title": "Sample title 1", "description": "<html>code</htm

我有这样的目标:

{
  "id": 1,
  "name": "first",
  "sections": [
    {
      "id": 1,
      "title": "First section",
      "contents": [
        {
          "id": "123",
          "title": "Sample title 1",
          "description": "<html>code</html>",
        },
        {
          "id": "124",
          "title": "Sample title 2",
          "description": "<html>code</html>"
        },
        {
          "id": "125",
          "title": "Some other sample",
          "description": "<html>code</html>"
        }
      ]
    },
    {
      "id": 2,
      "title": "Second section",
      "contents": [
        {
          "id": "126",
          "title": "Sample title 126",
          "description": "<html>code</html>"
        },
        {
          "id": "127",
          "title": "Sample title 127",
          "description": "<html>code</html>"
        }
      ]
    }
  ]
}
在上面的代码中,console.logsections返回未定义。如何获取节数组中的位置,该数组包含具有特定id的内容数组。例如,id:125将返回节位置0,因此我可以使用splice删除该元素


如果我的方法完全错误,请为我指出正确的方向,谢谢:

您只需要使用forEach的第二个参数:

您可以使用而不是.splice。过滤器将保留您为其返回true的所有项目,并丢弃您为其返回false的所有项目。因此,如果当前节的内容对象的id等于要删除的id,则可以返回false以删除它,否则返回true以保留该项。可以使用此选项将每个节对象映射到具有更新内容数组的新对象:

const obj={id:1,name:first,sections:[{id:1,title:first section,contents:[{id:123,title:Sample title 1,description:code,},{id:124,title:Sample title 2,description:code},{id:125,title:Some-other-Sample,description:code}]},{id:2,title:Second section,contents:[{id:126,title:Sample title 126,description:code},{id:127,title:Sample title 127,description:code}]}; 常数idToRemove=125; obj.sections=obj.sections.map sec=>{…sec,contents:sec.contents.filter{id}=>id!=idToRemove} ; console.logobj;
。作为控制台包装器{max height:100%!important;top:0;}/*ignore*/为什么不使用一个简单的筛选器来完成任务。此外,它将是一种更干净、更不变的方法

let newArrWithoutContentWithGivenId = obj.sections.map(section =>
     ({...section, contents: section.contents.filter(content => 
         content.id != 125)}));
这里,我们映射内容不包含ID125的每个节。简而言之,section>content.ID!=125将从新数组中删除

希望有帮助:

注意:代码没有经过测试,只是为了帮助您找到一种干净的方法

obj.sections.forEach(function(section, sectionIndex) {
    section.contents.forEach((content, contentIndex) => {
        if (content.id == 125) {
            // use the sectionIndex and contentIndex to remove
        }
    })
})
let newArrWithoutContentWithGivenId = obj.sections.map(section =>
     ({...section, contents: section.contents.filter(content => 
         content.id != 125)}));