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?

asked Apr 18, 2017 at 14:49

3 Answers 3

6

Use map function:

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

Link:

Array.prototype.map

answered Apr 18, 2017 at 14:51

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/

answered Apr 18, 2017 at 14:54

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

answered Apr 18, 2017 at 14:53

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.