簡體   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