-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'
}
13
  • 6
    Its because it is an array Commented Jun 10, 2016 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. Commented Jun 10, 2016 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. Commented Jun 10, 2016 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. Commented Jun 10, 2016 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. Commented Jun 10, 2016 at 16:25

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.