过滤对象javascript内的数组

时间:2018-02-23 10:39:59

标签: javascript filter

也许是星期五早上我有一点时间,但不知道为什么这不起作用。

我有这个JSON

var recipes = [{
            name: "Beef Lasagne",
            ingredients: [
                "mince",
                "pasta",
                "sauce",
                "tomatoes"
            ]}]

我可以这样做:recipes.filter(recipe => recipe.name.includes('e'))并且过滤正确

然而,当我尝试这样做时:recipes.filter(recipe => recipe.ingredients.includes('e'))

我想尝试过滤ex1中的字符串,然后在ex2中过滤一个数组,我还需要做些什么来使第二个过滤器工作?

3 个答案:

答案 0 :(得分:2)

Array.includes()会查找特定元素。由于成分也是一个数组,你也需要遍历成分数组。

因此,如果成分等于:

,它只会起作用
    ingredients: [
        "mince",
        "pasta",
        "sauce",
        "tomatoes",
        "e"
    ]

所以你可能想要这样的东西:

recipes.filter( recipe => recipe.ingredients.some( ingredient => ingredient.includes( 'e' ) ) );



var recipes = [{
    name: "Beef Lasagne",
    ingredients: [
      "mince",
      "pasta",
      "sauce",
      "tomatoes"
    ]
  },
  {
    name: "Beef Lasagne without e",
    ingredients: [
      "minc",
      "past",
      "tomatos"
    ]
  },
  {
    name: "Beef Lasagne with sauce and no mince",
    ingredients: [
      "sauce",
      "pasta",
      "tomatoes"
    ]
  }
]

console.log(
    recipes.filter( recipe => recipe.ingredients.some( ingredient => ingredient.includes( 'e' ) ) )
)
console.log(
    recipes.filter( recipe => recipe.ingredients.some( ingredient => ingredient.startsWith( 'min' ) ) )
)




答案 1 :(得分:0)

您可以在数组上使用With Sheets("My Sheet") ' reference wanted sheet With Range(.Cells(RowStart, ColStart), .Cells(RowFinish, ColFinish)) ' reference referenced sheet range .Parent.Cells(myRow, myCol).Resize(.Rows.Count, .Columns.Count).Value = .Value 'copy referenced range values only and paste them starting from referenced sheet cells(myRow, myCol) End With End With 将其转换为字符串,并且能够以您最初想要的方式使用.join("")

.includes()

答案 2 :(得分:0)

试试这个:

recipes.filter(recipe => recipe.ingredients.filter(ingredient => ingredient.includes('e')).length > 0)