【问题标题】:JavaScript Array Filtering in Nested Arrays嵌套数组中的 JavaScript 数组过滤
【发布时间】:2022-08-17 16:21:48
【问题描述】:

我有一个看起来像这样的数组:

const arrayObj = [
    {
        id: 1,
        itemsList: [
            {
                name: \"Paul\",
            },
            {
                name: \"Newman\",
            },
        ],
    },
    {
        id: 2,
        itemsList: [
            {
                name: \"Jack\",
            },
            {
                name: \"Man\",
            },
        ],
    },
]

我想要的是过滤其 itemsList 包含具有特定值名称的对象的对象。例如,我希望能够过滤出一个包含对象的数组,其内部对象的名称包含 \"ul\"(在本例中,名称 Paul 包含 \"ul\"),它应该给我这样的输出:

const outputArray = [
    {
        id: 1,
        itemsList: [
            {
                name: \"Paul\",
            },
            {
                name: \"Newman\",
            },
        ]
    }
]

到目前为止,我只能用这个函数过滤出一个简单的平面对象数组:

function filterByName(array: any, string: any) {
    return array.filter((obj: any) =>
      [\"name\"].some((key: any) =>
        String(obj[key]).toLowerCase().includes(string.toLowerCase())
      )
    );
}

但我不知道如何将它应用到我的案例中。

标签: javascript arrays


【解决方案1】:

在这里您可以使用some methodincludes method 结合使用

const arrayObj = [{
    id: 1,
    itemsList: [{
        name: "Paul",
      },
      {
        name: "Newman",
      },
    ],
  },
  {
    id: 2,
    itemsList: [{
        name: "Jack",
      },
      {
        name: "Man",
      },
    ],
  },
]


const getFilterArray = (name) => {
  return [...arrayObj.filter(obj => obj.itemsList.some(x => x.name.toLowerCase().includes(name.toLowerCase())))]
}

console.log(getFilterArray("ul"))

【讨论】:

    猜你喜欢
    • 2020-08-25
    • 1970-01-01
    • 2016-10-28
    • 2022-08-19
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多