Vasilis Greece
Vasilis Greece

Reputation: 907

Convert json data to javascript array

I want to convert json data and put the return values into javascript array. I use jquery version 1.9.1

jquery:

$('#searchinput').on('keyup', function(){
      $value2=$(this).val();
      $.ajax({
        type: 'get',
        url: '{{URL::to('search')}}',
        data: {'thesearch':decodeURIComponent($value2)},
        success:function(game){              
          alert(JSON.stringify(game));
        }
      });
    });

That gives the result:

[{"name":"First name"},{"name":"Second Name"}]

What I want is to store the values into javascript array like this:

var namearray = ['First name', 'Second Name'];

How to do that?

Upvotes: 0

Views: 111

Answers (3)

Muhammad Qasim
Muhammad Qasim

Reputation: 1712

Did you give a try using map function? You can do the following:

var nameArray = game.map(name => name["name"]);

So your whole code becomes like:

$('#searchinput').on('keyup', function(){
    $value2=$(this).val();
    $.ajax({
      type: 'get',
      url: '{{URL::to('search')}}',
      data: {'thesearch':decodeURIComponent($value2)},
      success:function(game){        
         var nameArray = game.map(name => name["name"]);
    }});
});

Hope this helps :)

Upvotes: 2

cpap
cpap

Reputation: 82

You can use the jquery map function

$.map([{"name":"First name"},{"name":"Second Name"}], function(val, i){return val.name})

read more about that http://api.jquery.com/jquery.map/

Upvotes: 4

user4074041
user4074041

Reputation:

Use map function:

var namearray = arr.map(x => x.name);

Link:

Array.prototype.map

Upvotes: 6

Related Questions