【问题标题】:Filtering a nested array and return the array which matches the value for the key过滤嵌套数组并返回与键值匹配的数组
【发布时间】:2021-11-21 05:47:03
【问题描述】:

我正在尝试根据 id 过滤包含对象数组的数组。 我可以过滤它们,但需要稍微清理一下输出,因为它还返回一个空数组,因为条件与该数组不匹配。

我该如何解决?

const resKey = 'ABC';
const data = [
  [{
    "user": {
      "firstName": "John",
      "lastName": "Smith",
    },
    "id": "ABC"
  }],
  [{
    "user": {
      "firstName": "John",
      "lastName": "Smith",
    },
    "id": "DEF"
  }]
];

const result = data.map(eachArr => eachArr.filter(eachObj => eachObj.id === resKey));
console.log(result);

预期输出:

[
  [
    {
      user: {
        firstName: "John",
        lastName: "Smith",
      },
      id: "ABC",
    },
  ],
]

实际输出:

[
  [
    {
      user: {
        firstName: "John",
        lastName: "Smith",
      },
      id: "ABC",
    },
  ],
  [],
]

【问题讨论】:

    标签: javascript arrays object filter nested


    【解决方案1】:

    您可以再次使用filter 过滤掉不包含元素的空数组(length0)。

    .filter((arr) => arr.length);
    

    const resKey = "ABC";
    const data = [
      [
        {
          user: {
            firstName: "John",
            lastName: "Smith",
          },
          id: "ABC",
        },
      ],
      [
        {
          user: {
            firstName: "John",
            lastName: "Smith",
          },
          id: "DEF",
        },
      ],
    ];
    
    const result = data
      .map((eachArr) => eachArr.filter((eachObj) => eachObj.id === resKey))
      .filter((arr) => arr.length);
      
    console.log(result);

    【讨论】:

      猜你喜欢
      • 2021-12-13
      • 2022-01-25
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-12
      • 1970-01-01
      • 2017-03-08
      相关资源
      最近更新 更多