我有一个常见的问题,我想知道是否有人有比我到目前为止所做的更好的方法来解决它。
我想循环一个数组来查找一个对象并更新它。如果该对象不存在,我想将其附加到数组中。我通常处理更复杂的对象,这使得问题变得更加复杂。
var movies = [
{ _id: 1, title:"Movie 1" },
{ _id: 2, title: "Another Movie" }
];
var myTheater = { location:"here", current_movies: movies };
// A movie to check. The _id may or may not be in movies.
var aMovie = { _id: 3, title: "Something New" };
// boolean flag to let us know if something happened
var updated = false;
// look through all movies and my theater and update as needed
for(var i = 0, len = myTheater.current_movies.length; i<len; i++){
if( myTheater.current_movies[i]._id === aMovie._id ){
console.log("Updating movie name.");
myTheater.current_movies[i].title = aMovie.title;
updated = true;
break;
}
}
// check if anything was updated and add the movie if not
if(!updated){
myTheater.current_movies.push(aMovie);
}
有没有更好的方法来做到这一点,或者使用标志是最好的选择?谢谢!
使用原生的Array.prototype.find https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find像这样:
var movies = [{ _id: 1, title:"Movie 1" }, { _id: 2, title: "Another Movie" }];
var myTheater = { location:"here", current_movies: movies };
var aMovie = { _id: 3, title: "Something New" };
// check if there is a movie with the same id as aMovie
var found = myTheater.current_movies.find(m => m._id == aMovie._id);
if(found) // if we found something
found.title = aMovie.title; // update it's title
else
/*things to do if nothing was found*/
console.log("nothing found!");
箭头功能:
我传递给的函数(回调)find
叫做箭头功能 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions。您可以致电find
使用像这样的常规函数:
var found = myTheater.current_movies.find(function(m) {
return m._id == aMovie._id;
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)