我从一个存储在变量console_log
中的数组(来自cbsaList
)开始:
[Object, Object, Object]
0: Object
cbsa name: "Dothan, AL"
1: Object
cbsa name: "Gadsden, AL"
2: Object
cbsa name: "Birmingham-Hoover, AL"
length: 3
我试图将3 cbsa name
s作为逗号分隔的字符串。
我已经尝试了这个,但它还是以未定义的方式回归:
var all_cbsa =[];
$.each(data, function(i, cbsaList) {
all_cbsa.push(cbsaList['cbsa name']);
console.log(all_cbsa); //undefined
});
我在这里搞砸了什么?
答案 0 :(得分:0)
这是一个同步版本:
var data = [
{
cbsa_name:'test'
},
{
cbsa_name:'test2'
}
];
function buildListFromArrayByKey(arr, key) {
var result = "";
var len = arr.length - 1;
for(var i = 0; i <= len; i++) {
//if its the last index don't add a comma
if(i == len) {
result += arr[i][key];
}else{
//add coma
result += arr[i][key] + ',';
}
}
return result;
}
var list = buildListFromArrayByKey(data,'cbsa_name');