gpt4 book ai didi

javascript - 使用正则表达式计算对象中的数组项

转载 作者:行者123 更新时间:2023-12-03 03:00:02 25 4
gpt4 key购买 nike

所以我有一个对象:

   var data = {
"movies": {
"first": {
"title": "Bruce Almigthy",
"actors": ["Jim Carrey", "Morgan Freeman", "Jennifer Aniston"],
"year": "2003"
},
"second": {
"title": "The Truman Show",
"actors": ["Jim Carrey", "Ed Harris","Morgan Freeman", "Laura Linney"],
"year": "1998"
},
"third": {
"title": "Ace Ventura",
"actors": ["Jim Carrey", "Courteney Cox","Ed Harris"],
"year": "1994"
}
}
};

console.log(data.movies);

我需要找到出演过 1 部电影以上的 Actor ,以及只出演过一部电影的 Actor 。我通常用这样的方法处理此类问题:

function countMax(data) { 

var actors = {};

Object.keys(data.movies).forEach(function (key) {
var movie = data.movies[key];

movie.actors.forEach(function (actor) {
if (!actors.hasOwnProperty(actor)) actors[actor] = 0;
actors[actor]++;
})

})

Object.keys(actors).forEach(function (actor) {

var count = actors[actor];
if (count > 1) console.log(actor + ' stars in ' + count + ' movies.');

});

};

countMax(data);

我想知道是否有不同的方法可以做到这一点,也许使用正则表达式或类似的东西?我只是不确定如何“接近”该物体。

最佳答案

我认为正则表达式不会为您做太多事情,但是您可以利用现代 Javascript 的一些优点来缩短一些事情。例如,您可以使用以下方法制作 Actor 和计数的 map :

var actor_map = Object.values(data.movies).reduce((a, c) => {
c.actors.forEach(i => a[i] = a[i] ? a[i]+1 : 1 )
return a
}, {})

然后您可以过滤计数以获得您想要的任何内容:

var more_that_one = Object.entries(actor_map).filter(([k, v]) => v > 1)
var less_that_one = Object.entries(actor_map).filter(([k, v]) => v == 1)

var data = {
"movies": {
"first": {
"title": "Bruce Almigthy",
"actors": ["Jim Carrey", "Morgan Freeman", "Jennifer Aniston"],
"year": "2003"
},
"second": {
"title": "The Truman Show",
"actors": ["Jim Carrey", "Ed Harris","Morgan Freeman", "Laura Linney"],
"year": "1998"
},
"third": {
"title": "Ace Ventura",
"actors": ["Jim Carrey", "Courteney Cox","Ed Harris"],
"year": "1994"
}
}
};

var actor_map = Object.values(data.movies).reduce((a, c) => {
c.actors.forEach(i => a[i] = a[i] ? a[i]+1 : 1 )
return a
}, {})

var more_that_one = Object.entries(actor_map).filter(([k, v]) => v > 1)
var less_that_one = Object.entries(actor_map).filter(([k, v]) => v == 1)

console.log(more_that_one)
console.log(less_that_one)

关于javascript - 使用正则表达式计算对象中的数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47446013/

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