-2

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'
}
George
  • 5,808
  • 15
  • 83
  • 160
  • 6
    Its because it is an array – Adam Buchanan Smith Jun 10 '16 at 16:13
  • 6
    The desired result isn't a valid object. You'd probably have to manually build that representation as a string. It's not really clear what you're actually trying to accomplish here. – David Jun 10 '16 at 16:17
  • 1
    Besides you can't have just names: { 'Mike', 'Rik', 'Tom' }, as all values inside names would become key, and they need to have values. – Don Jun 10 '16 at 16:19
  • 1
    Seconding what @David said, an object in javascript is like a map in java, meaning there has to be a value mapped to a key. what you want is not a valid object. – Rahul Sharma Jun 10 '16 at 16:19
  • Objects are key-value pairs. So for each key (`'Mike', 'Rik', 'Tom'`) you need a matching value (`'Mike': 'C'`). If you just want a list of "keys" with no matching values, then you want an array. – Mike Cluck Jun 10 '16 at 16:25
  • @MikeC:I edited my question.If you want to check it .Thanks! – George Jun 10 '16 at 16:58
  • @David:I edited my question.If you want to check it .Thanks! – George Jun 10 '16 at 16:58
  • @George Objects can't have duplicate keys. You can't have one object with multiply `name` keys. Maybe you should try telling us what you're actually trying to accomplish, not how you think the data should be formatted. – Mike Cluck Jun 10 '16 at 16:59
  • @MIkeC:yes,mistake.I removed it.I guess what I want to do can't be done,right? – George Jun 10 '16 at 17:01
  • @George Why do you think you want an object that only has a bunch of strings in it? What you want is an array and that's totally possible. – Mike Cluck Jun 10 '16 at 17:02
  • @George: It depends on what you're actually trying to do, a subject on which you've been pretty quiet. You can't use invalid syntax, that much is certain. Technically duplicate keys *are* valid syntax, but are pretty useless as far as objects go (http://stackoverflow.com/a/19927061/328193). – David Jun 10 '16 at 17:02
  • Ok ,thank you all.I will think how to do it right and I will let you know.I know it is possible with arrays – George Jun 10 '16 at 17:04
  • @MikeC:I opened another [thread](http://stackoverflow.com/questions/37755532/create-object-with-proper-format-from-csv) – George Jun 10 '16 at 19:06

1 Answers1

0

You could use this function to get an array of values, not object properties (which are not suited for that):

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);
trincot
  • 317,000
  • 35
  • 244
  • 286