extract fields from object

时间:2016-06-10 16:12:52

标签: javascript

If I have this:

var myObj = [
  { name: 'A', number: 'b1',level: 0 },
  { name: 'B', number: 'b2',level: 0 },
];

How can I extract all the names like:

"names": {
  'A',
  'B'
}

1 个答案:

答案 0 :(得分:0)

你可以使用这个函数来获取值的数组,而不是对象属性(不适合它):

function getColumn(arr, column) {
    return arr.map(function (rec) { return rec[column] });
}

// Sample data
var myObj = [
  { name: 'A', number: 'b1',level: 0 },
  { name: 'B', number: 'b2',level: 0 },
];

// Get names
var names = getColumn(myObj, 'name');

// Output
console.log(names);