循环对象里面的数组里面的数组JavaScript对象

时间:2017-05-12 10:29:11

标签: javascript arrays loops ecmascript-6

我试图将数组内部的对象循环到数组内的对象中,我真的很困惑!

这是我的arr:

var arr = [
{
title: "Harry Potter",
categories: [
{
id: 39,
name: "Popular Books"
},
{
id: 3,
name: "Kids"
},
{
id: 79,
name: "All Books"
}
]
},


{
title: "Pride and Prejudice",
categories: [
{
id: 36,
name: "Classic Books"
},
{
id: 3,
name: "Woman"
},
{
id: 79,
name: "All Books"
}
]
}
]

如何获得只有类别名称为“儿童”的图书标题?

现在我能想到的只有:

var find = function(arr){
  for(var i=0; i<arr.length; i++){
    for(var j=0; j<arr[i].categories; j++){
      console.log(arr[i].categories[j].name)
    }
  }
}

哪个超级脏,无论如何都不起作用。 谢谢!

2 个答案:

答案 0 :(得分:4)

你可以使用过滤器来过滤那些类别与“Kids”匹配的数组元素,然后他们的标题映射到一个新数组中。

arr.filter( i => i.categories.some(j => j.name ==="Kids") ).map(k => k.title )

var arr = [{
    title: "Harry Potter",
    categories: [{
        id: 39,
        name: "Popular Books"
      },
      {
        id: 3,
        name: "Kids"
      },
      {
        id: 79,
        name: "All Books"
      }
    ]
  },


  {
    title: "Pride and Prejudice",
    categories: [{
        id: 36,
        name: "Classic Books"
      },
      {
        id: 3,
        name: "Woman"
      },
      {
        id: 79,
        name: "All Books"
      }
    ]
  }
];

console.log(arr.filter(i => i.categories.some(j => j.name === "Kids")).map(k => k.title));

答案 1 :(得分:1)

试一试:

align-items-end