代码之家  ›  专栏  ›  技术社区  ›  Mithilesh choubey

基于值从JavaScript中的嵌套JSON数组对象中筛选/删除数组对象

  •  -3
  • Mithilesh choubey  · 技术社区  · 11 月前

    我有一个筛选条件要应用于REST响应。此响应具有嵌套的子对象。对于正在进行的循环,任务和筛选器函数不适用于嵌套数组对象。请帮助我根据body.items[index].details.items[idex]筛选以下JSON数组对象。Id值。

    因此,在这里,我希望只保留body.items.details.items中与300100619883728匹配的数组。

    JSON:

    {
        "error": null,
        "message": {
          "summary": ""
        },
        "status": 200,
        "headers": {},
        "body": {
          "items": [
            {
              "Name": "Test1",
              "LastName": "ABC",
              "details": {
                "items": [
                  {
                    "Id": "300100619883728",
                    "Status": "Draft",
                    "subDetails": {
                      "items": [
                        {
                          "CurrentAddress": "Some address"
                        }
                      ],
                      "totalResults": 1,
                      "count": 1,
                      "hasMore": false,
                      "limit": 25,
                      "offset": 0
                    }
                  },
                  {
                    "Id": "300100619883738",
                    "Status": "Draft",
                    "subDetails": {
                      "items": [
                        {
                          "CurrentAddress": "Some Address"
                        }
                      ],
                      "totalResults": 1,
                      "count": 1,
                      "hasMore": false,
                      "limit": 25,
                      "offset": 0
                    }
                  }
                ],
                "totalResults": 2,
                "count": 2,
                "hasMore": false,
                "limit": 25,
                "offset": 0
              }
            },
            {
              "Name": "Test2",
              "LastName": "ABC",
              "details": {
                "items": [
                  {
                    "Id": "300100619883728",
                    "Status": "Draft",
                    "subDetails": {
                      "items": [
                        {
                          "CurrentAddress": "Some address"
                        }
                      ],
                      "totalResults": 1,
                      "count": 1,
                      "hasMore": false,
                      "limit": 25,
                      "offset": 0
                    }
                  },
                  {
                    "Id": "300100619883739",
                    "Status": "Draft",
                    "subDetails": {
                      "items": [
                        {
                          "CurrentAddress": "Some Address"
                        }
                      ],
                      "totalResults": 1,
                      "count": 1,
                      "hasMore": false,
                      "limit": 25,
                      "offset": 0
                    }
                  }
                ],
                "totalResults": 2,
                "count": 2,
                "hasMore": false,
                "limit": 25,
                "offset": 0
              }
            }
          ],
          "totalResults": 2
        },
        "ok": true,
        "statusText": "OK"
      }
    

    筛选后的预期结果是数组结构不变:

    {
        "error": null,
        "message": {
          "summary": ""
        },
        "status": 200,
        "headers": {},
        "body": {
          "items": [
            {
              "Name": "Test1",
              "LastName": "ABC",
              "details": {
                "items": [
                  {
                    "Id": "300100619883728",
                    "Status": "Draft",
                    "subDetails": {
                      "items": [
                        {
                          "CurrentAddress": "Some address"
                        }
                      ],
                      "totalResults": 1,
                      "count": 1,
                      "hasMore": false,
                      "limit": 25,
                      "offset": 0
                    }
                  }
                ],
                "totalResults": 2,
                "count": 2,
                "hasMore": false,
                "limit": 25,
                "offset": 0
              }
            },
            {
              "Name": "Test2",
              "LastName": "ABC",
              "details": {
                "items": [
                  {
                    "Id": "300100619883728",
                    "Status": "Draft",
                    "subDetails": {
                      "items": [
                        {
                          "CurrentAddress": "Some address"
                        }
                      ],
                      "totalResults": 1,
                      "count": 1,
                      "hasMore": false,
                      "limit": 25,
                      "offset": 0
                    }
                  }
                ],
                "totalResults": 2,
                "count": 2,
                "hasMore": false,
                "limit": 25,
                "offset": 0
              }
            }
          ],
          "totalResults": 2
        },
        "ok": true,
        "statusText": "OK"
      }
    

    filter我试图获得所需的结果,但无法访问嵌套对象的值和筛选器。

    const filteredObj = obj.body.items.filter(function (item) {
       return item.details.items == 300100619883728;
    });
    
    1 回复  |  直到 11 月前
        1
  •  2
  •   Kinan Dira    11 月前

    您打算做的并不像看上去那么简单:您不想过滤单个数组,而是要过滤多个数组( details.items )每个都位于作为更高数组成员的对象内部( body.items ).

    如果你不介意改变原始响应(这通常不是一个好的做法),下面的代码行就可以了。

    response.body.items.forEach(item => item.details.items = item.details.items.filter(item => item.Id === ID_TO_FIND));
    

    我们在这里说的是: 对于中的每个项目 body.items ,筛选该项目的 details.items 只保留那些想要的 Id .

    然而,更干净的解决方案是创建响应的新副本 body.items 其中每个 item s details.items 被过滤。以下是其工作原理:

    const ID_TO_FIND = "300100619883728"; // The id we want to keep
    
    // The map() function creates a new copy of an array,
    // while allowing us to change how each element in that copy looks like
    const fileterdBodyItems = response.body.items.map(item => { 
    
      // For each item in the body, we create a filtered copy of that item's details
      const fileterdDetailsItems = item.details.items.filter(item => item.Id === ID_TO_FIND)
    
      // Now, we create a new details object for that item, which uses all the original
      // attributes of the original details, except for items; we replace them with 
      // fileterdDetailsItems 
      const fileterdDetails = { ...item.details, items: fileterdDetailsItems };
    
      // Like the above, we want the filtered item to contain all the original
      // attributes of the original item, except for details, replacing them with
      // filtered details
      const filteredItem = { ...item, details: fileterdDetails };
    
      // Each object returned from the map() function's callback will become one
      // element in fileterdBodyItems
      return filteredItem ;
    });
    
    // This should be familiar by now
    const fileterdBody = {...response.body, items: fileterdBodyItems};
    const filteredResponse = {...response, body: fileterdBody}