[英]get array of attribute from an array of objects
Say i have an array of objects in javascript as假设我在 javascript 中有一个对象数组
var array=[{id:1,message:"hello",time:"00-00-0000"},{id:2,message:"sup",time:"00-00-0000"},...];
What is the best way to get an array only containing the message attribute.获取仅包含消息属性的数组的最佳方法是什么。 ie
IE
var messages=["hello","sup",...];
The "best" way would be: “最好”的方式是:
var messages = array.map(function(x) {return x.message;});
The most compatible way:最兼容的方式:
for(var messages=[],i=0,l=array.length; i<l; i++) messages[i]=array[i].message;
var messages = [];
for(var i = 0; i < array.length; i++) {
messages.push(array[i][1]);
}
@Niet the Dark Absol 解决方案的更简洁、更现代的变体是:
const messages = array.map(x => x.message);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.