gpt4 book ai didi

javascript - 如何获取对象数组中的值?

转载 作者:行者123 更新时间:2023-11-28 14:10:51 29 4
gpt4 key购买 nike

我想从下面的数组中收集评分高于 3 的所有电影 ID

let movies = [
{'name': 'Actions', 'movies': [{'id': 1, 'rating': 2},
{'id': 2, 'rating': 1},
{'id': 3, 'rating': 4}]},
{'name': 'Comedy', 'movies': [{'id': 4, 'rating': 3},
{'id': 5, 'rating': 4},
{'id': 6, 'rating': 5}]},
{'name': 'Sci-fi', 'movies': [{'id': 7, 'rating': 1},
{'id': 8, 'rating': 5},
{'id': 9, 'rating': 2}]}
];

我从下面的代码中获取了评级高于 3 的 id

let res = movies
.map( m => m.movies
.filter( f => f.rating > 3 )
)
.flat();
console.log(res);

输出

[[object Object] {
id: 3,
rating: 4
}, [object Object] {
id: 5,
rating: 4
}, [object Object] {
id: 6,
rating: 5
}, [object Object] {
id: 8,
rating: 5
}]

如何从输出中删除 [object Object] rating 并仅获取扁平 id 数组?

最佳答案

使用Array.flatMap()将电影平铺到一个数组中,按评分进行过滤,然后映射到id:

const movies = [{"name":"Actions","movies":[{"id":1,"rating":2},{"id":2,"rating":1},{"id":3,"rating":4}]},{"name":"Comedy","movies":[{"id":4,"rating":3},{"id":5,"rating":4},{"id":6,"rating":5}]},{"name":"Sci-fi","movies":[{"id":7,"rating":1},{"id":8,"rating":5},{"id":9,"rating":2}]}];

const result = movies
.flatMap(m => m.movies)
.filter(m => m.rating > 3)
.map(m => m.id);

console.log(result);

关于javascript - 如何获取对象数组中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59552527/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com