如何在没有 jQuery的数组中获取键的所有值?
var species = [{"code_name":"b","public_name":"a"},{"code_name":"d","public_name":"c"},{"code_name":"f","public_name":"e"}];
var speciesVals = Object.keys(species).map(function (val, key) {
return val;
});
结果:
[ '0',
'1',
'2',
'_atomics',
'_parent',
'_cast',
'_markModified',
'_registerAtomic',
'$__getAtomics',
'hasAtomics',
'_mapCast',
'push',
'nonAtomicPush',
'$pop',
'pop',
'$shift',
'shift',
'pull',
'splice',
'unshift',
'sort',
'addToSet',
'set',
'toObject',
'inspect',
'indexOf',
'remove',
'_path',
'isMongooseArray',
'validators',
'_schema' ]
但我在追求:
["code_name":["b", "d", "d"], "public_name":["a", "c", "e"]
有可能吗?
修改
这个怎么样:
[{"code_name":["b", "d", "d"]}, {"public_name":["a", "c", "e"}]
答案 0 :(得分:3)
使用JavaScript Array#reduce
方法。
var species = [{
"code_name": "b",
"public_name": "a"
}, {
"code_name": "d",
"public_name": "c"
}, {
"code_name": "f",
"public_name": "e"
}];
var temp = species.reduce(function(res, v) {
// iterate over object(array element)
Object.keys(v).forEach(function(k) {
// define property as array if not defined
res[k] = res[k] || [];
// push the value to prefered array
res[k].push(v[k]);
});
// return the updated object
return res;
// define the initial value as object to hold the result
}, {});
// now create your expected result
var speciesVals = Object.keys(temp) // get all property names
.map(function(v) { //iterate over them to generate the result array
var obj = {}; // create object for
obj[v] = temp[v]; // add property
return obj; // return object (which is the new array element)
});
console.log(speciesVals);

答案 1 :(得分:1)
当然有可能。如果对象键对于数组中的每个对象都相同,则可以执行以下操作:
var species = [{"code_name":"b","public_name":"a"},{"code_name":"d","public_name":"c"},{"code_name":"f","public_name":"e"}];
var res = {code_name: [], public_name: []};
for(var i = 0; i < species.length; i++){
res.code_name.push(species[i].code_name);
res.public_name.push(species[i].public_name);
}
console.log(res);
修改
获取对象数组:
var species = [{"code_name":"b","public_name":"a"},{"code_name":"d","public_name":"c"},{"code_name":"f","public_name":"e"}];
var res = [{code_name: []}, {public_name: []}];
for(var i = 0; i < species.length; i++){
res[0].code_name.push(species[i].code_name);
res[1].public_name.push(species[i].public_name);
}
console.log(res);
答案 2 :(得分:1)
我建议为属性使用固定数组,因为您只需要'code_name
和public_name
。
var species = [{ "code_name": "b", "public_name": "a" }, { "code_name": "d", "public_name": "c" }, { "code_name": "f", "public_name": "e" }],
speciesVals = {};
species.forEach(function (a) {
['code_name', 'public_name'].forEach(function (k) {
speciesVals[k] = speciesVals[k] || [];
speciesVals[k].push(a[k]);
});
});
console.log(speciesVals);