将字典键值添加到数组[JavaScript]

时间:2017-06-13 10:44:57

标签: javascript angularjs arrays dictionary

以下是 JavaScript

中我的数据结构示例
var list = [{"username":"admin1"}, {"username":"admin2"}, {"username":"admin3"}, 
{"username":"admin4"}, {"username":"admin5"}];

如何将每个“用户名”添加到新数组(var result = [])?

最终数据结构的样本将是:

var result = ["admin1", "admin2", "admin3", "admin4", "admin5"];

谢谢*

2 个答案:

答案 0 :(得分:5)

使用Array#map方法通过迭代元素来生成数组。



var list = [{"username":"admin1"}, {"username":"admin2"}, {"username":"admin3"}, 
{"username":"admin4"}, {"username":"admin5"}];

var res = list.map(function(o) {
  return o.username
});

console.log(res);




使用ES6 arrow function



var list = [{"username":"admin1"}, {"username":"admin2"}, {"username":"admin3"}, 
{"username":"admin4"}, {"username":"admin5"}];

let res = list.map(o => o.username);

console.log(res);




答案 1 :(得分:1)

var list = [{"username":"admin1"}, {"username":"admin2"}, {"username":"admin3"}, 
{"username":"admin4"}, {"username":"admin5"}];
var array=[];

 for (var key in list) {
    let value = list[key];
    console.log(value.username);
    array.push(value.username);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>