JavaScript中对象的Array.prototype.map()等价于什么
我正在尝试从原始对象中取出一些对象到数组variables中。
console.log("news len", news["articles"].length); // this comes out to 9 for(var a in news["articles"]) { var results = []; results.push({ title:news["articles"][a]["title"], subtitle: news["articles"][a]["description"], item_url:news["articles"][a]["title"], image_url:news["articles"][a]["urlToImage"], }); } console.log("results len",results.length); //only contains one entry
有没有另一种方法来实现这一点,如果不是我做错了什么?
使用Node js,如果有帮助的话。
您可以直接使用map,并在callback中返回一个新对象
var results = news.articles.map(function (a) { return { title: a.title, subtitle: a.description, item_url: a.title, image_url: a.urlToImage }; };
主要的问题是你的循环的每次迭代都会将results
重新设置为一个空数组:
var results=[];
如果你在循环之前移动语句,你会得到更接近你想要的东西。
这就是说,它看起来像news["articles"]
已经是一个数组,所以你可以只使用Array.prototype.map
?
var results = []; news["articles"].map(function(val,idx){ results.push({ title: val["title"], //etc } });