Search code examples
javascriptarraysjsonnode.jsnode-mysql

Converting a JSON object to array? Read description


my server upon request, serves JSON from a node mysql query, but only the names row. Example:

{
"Name": "Charles"
}, etc. 

How can I, get the value of Name and put it into an array? say I have this,

  [
 {
  "Name": "Charles"
 },
 {
  "Name": "Alex"
 }
  ]

how can I get, Charles and Alex, into an array?

Like:

Names = ["Charles", "Alex]? 

Solution

  • You can make use of the map function. The map method creates a new array with the results of calling a provided function on every element in this array. In your case, you need to select only the Name.

    var arr = [
     {
      "Name": "Charles"
     },
     {
      "Name": "Alex"
     }];
      
    var names = arr.map(x=>x.Name)
    console.log(names);