0

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?

3 Answers 3

6

Use map function:

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

Link:

Array.prototype.map

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

Comments

4

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/

Comments

2

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

2 Comments

with JSON.parse(game) didn't work .. So far it works that... var nameArray = game.map(name => name["name"]);
updated my answer.My Upvote to your comment. Thanks :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.