繁体   English   中英

如何通过嵌套在对象数组的属性中的对象属性的值在对象数组中找到多个索引?

[英]How to find multiple indexes in array of objects by the value of an object property that nests in a property of array of objects?

我有一个对象数组,每个对象都有一个“监视”属性,它本身就是一个对象数组。

let arr = 
        [ 
            {   
                id: 1, 
                name: "A", 
                watched: [ 
                            {movieId: 7, movieName: "Avatar"} , 
                            {movieId: 8, movieName: "Titanic"}
                        ]
            },
            {   
                id: 2, 
                name: "B", 
                watched: [   
                            {movieId: 1, movieName: "Armageddon"} , 
                            {movieId: 8, movieName: "Titanic"}
                        ]
            },
            {   
                id: 3, 
                name: "C", 
                watched: [   
                            {movieId: 1, movieName: "Armageddon"} , 
                            {movieId: 7, movieName: "Avatar"}
                        ]
            }

        ]

我需要根据给定的 MovieId 的索引数组。 如果我想要一个观看电影的索引数组,没有。 7(阿凡达) - 我会得到:

让 AvatarWatchers = [0,2]

我试过:

AvatarWatchers = arr.filter((item) => item.watched.find(movieObj => movieObj.movieId == 7) > -1 )

但它不起作用,我得到了一个空数组。

 let arr = [ { id: 1, name: "A", watched: [ {movieId: 7, movieName: "Avatar"} , {movieId: 8, movieName: "Titanic"} ] }, { id: 2, name: "B", watched: [ {movieId: 1, movieName: "Armageddon"} , {movieId: 8, movieName: "Titanic"} ] }, { id: 3, name: "C", watched: [ {movieId: 1, movieName: "Armageddon"} , {movieId: 7, movieName: "Avatar"} ] } ]; let result = arr.map((item, index) => ({...item, index})) .filter(item => item.watched.find(watchedItem => watchedItem.movieName === 'Avatar')) .map(item => item.index); console.log('expected result', result);

暂无
暂无

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

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