Javascript获取数组中键的所有值?

标签 javascript

如何不使用 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"}]

最佳答案

使用 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);

关于Javascript获取数组中键的所有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38564137/

相关文章:

javascript - Google Map API 路线请求限制

javascript - macOS Safari 无法从弹出窗口读取 localStorage 值

javascript - 你如何触发 Angular 砌体的重新加载?

javascript - jQuery 动画数组跳到最后

javascript - 使用 D3js 在 SVG 中使用 tspan 说明符选择文本元素的内容

javascript - jquery 在可排序时更改类

javascript - 在同一元素上使用 "controller as x"的多个 ng-controller 指令

javascript - Chrome打包应用存储错误

javascript - 在 View 中绑定(bind)数组元素

javascript - react-native 中的 clonewithrows 数组问题