简体   繁体   English

循环对象内的数组内的对象内的数组 JavaScript

[英]Loop Object inside array inside object inside array JavaScript

I am trying to loop Object inside array inside object inside array and I am really confused!我试图在数组内的对象内循环对象内的对象,我真的很困惑!

here is my arr:这是我的 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"
}
]
}
]

How do I get the title of books that only have category name "Kids"?如何获得只有类别名称“儿童”的书名?

Right now all I can think of is:目前我能想到的只有:

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)
    }
  }
}

Which is super dirty and does not work anyway.这是超级脏,无论如何都不起作用。 Thank you!谢谢!

You could use filter to filter out those array elements with categories matching "Kids", then map their titles into a new array.您可以使用 filter过滤掉那些类别匹配“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));

have a try:试试:

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

find(arr, 'Kids')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM