0

I am using felixge/node-mysql to run this query: "SELECT DISTINCT tablename.id FROM tablename"

The rows returned are (obviously) in this format: [{id: 123},{id: 234},{id: 345}]

I can't figure out how to get this: [123, 234, 345]

3
  • 1
    developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… --- it must be the first thing you learn before you write any program in js. Also relevant: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jul 21, 2014 at 22:46
  • Thanks for the tip @zerkms, I was just looking for a shorter way than looping and extracting myself. Commented Jul 21, 2014 at 22:59
  • you should have stated that explicitly, we obviously cannot read your minds. "I can't figure out" doesn't correlate with what you've just said. Commented Jul 21, 2014 at 22:59

2 Answers 2

1

With ES5, such is rather easy using a map transformation:

The map() method creates a new array with the results of calling a provided function on every element in this array.

For example:

var arr = [{id: 123},{id: 234},{id: 345}];
var res = arr.map(function (o) {
   return o.id;
});

Doing this "manually" with a loop would look like so:

var arr = [{id: 123},{id: 234},{id: 345}];
var res = [];
// Loop over the array
for (var i = 0; i < arr.length; i++) {
  var item = arr[i];
  // And add new value we want to result array
  res.push(item.id);
}

(Note that the variables are function-scoped, but I prefer to use "close placement" of var.)

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

1 Comment

Upvoted because correct, but OP still won't become a better developer from this answer. Would be amazing if an alternative with explicit loop and array .push() was added.
0

You could use lodash or underscore:

var _ = require('lodash'); // or 'underscore'

var a = [{id: 123},{id: 234},{id: 345}];

var b = _.pluck(a, 'id');

console.log(b); // [123, 234, 345] 

1 Comment

Just a .map() would be enough without requiring OP to bring a whole library for a trivial task.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.