admin管理员组文章数量:1432436
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!
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!
Share Improve this question asked May 12, 2017 at 10:29 EtoyaEtoya 2391 gold badge7 silver badges16 bronze badges 1- 1 Possible duplicate of Javascript: How to filter object array based on attributes? – Rajesh Commented May 12, 2017 at 10:36
2 Answers
Reset to default 5You 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));
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')
本文标签: Loop Object inside array inside object inside array JavaScriptStack Overflow
版权声明:本文标题:Loop Object inside array inside object inside array JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745565086a2663711.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论