1

I am trying to loop Object inside array inside object inside array and I am really confused!

here is my 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!

1

2 Answers 2

5

You could use filter to filter out those array elements with categories matching "Kids", then map their titles into a new array.

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

Sign up to request clarification or add additional context in comments.

6 Comments

Yours is exactly same as mine. Didn't saw this answer.
Just a pointer, you are using 3 loops. .filter, .some and then .map. You can reduce iterations using .reduce + .some
If it helped you, consider accepting it as the answer.
definitely it helped, I accepted as the answer (did not even know I can do it))
Hi @dev8080: My requirement is almost same as this question. And i tried with your answer, too but am not getting the exact output. Can you please help me? jsfiddle.net/jasie/4jhd7zrs/10
|
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.