0

I want to create a array out of a JavaScript object, containing the values of all of the object's properties.

For example, given this object:

{
"firstName": "John",
"lastName": "Smith",
"isAlive": "true",
"age": "25"
}

I want to produce this array:

var myarray = ['John', 'Smith', 'true', '25'];

How can I do this?

user229044
  • 232,980
  • 40
  • 330
  • 338

4 Answers4

0

You could use the for … in loop, like so:

var obj = JSON.parse(input);
var array = [];
for (key in obj){
    array.push(obj[key]);
}
Aurel Bílý
  • 7,068
  • 1
  • 21
  • 34
  • not compatible in many browsers.. Some of them only supports `for...of`, others one not of both – Vincent Apr 14 '16 at 13:52
  • @Vincent Every browser supports `for... in`. The only problem here is with inherited enumerable keys, but that's a separate problem and can be avoided with `hasOwnProperty` and some (me included) find that level of paranoia to be extreme. – Ruan Mendes Apr 14 '16 at 13:58
  • The problem is that `$.getJSON('http://getapi.promike360.com/json.php')` outputs an object. When i log that object to the console. I can see at `responseText:....` the JSON output. But i don't know how to extract this value. – UNTITLED.PNG Apr 14 '16 at 14:10
  • So instead of the first line you would have `var obj = JSON.parse($.getJSON('http://getapi.promike360.com/json.php').responseText)`, no? – Aurel Bílý Apr 14 '16 at 14:12
  • @ProMike360 for that, see my answer (yes, this one that is at the bottom of the page...) – Vincent Apr 14 '16 at 14:12
  • and @JuanMendes I said that because I already had some problems with some browsers with this structure, so for myself I prefer use for() statement. – Vincent Apr 14 '16 at 14:15
  • @Aurel Bílý When i replace the new line you sugested, and `console.log(array);` i'm getting the error `VM655:1 Uncaught SyntaxError: Unexpected token u(anonymous function) @ test.html:5` – UNTITLED.PNG Apr 14 '16 at 14:22
  • @Vincent Without explaining what problem you had, your comment is not that useful – Ruan Mendes Apr 14 '16 at 14:50
  • @JuanMendes calm down! I just posted a comment, not opened a question! Also, I don't remember what was the context of this bug... I can just tell that since it I prefer to use the `for()` statement! After, you agree or disagree... – Vincent Apr 14 '16 at 14:55
  • @Vincent Calm down? Did I sound angry? Maybe you're mistaking my confusion that stemmed from your comment. I'm just explaining to you that it's not polite to say "this doesn't work" and not explain why. A simple `for` does not give you the keys of an object, your comment doesn't make sense. – Ruan Mendes Apr 14 '16 at 15:48
  • @JuanMendes yes, you sound angry by the roughness of yours comments! I'm just trying to help improve this answer by giving my opinion about this, and what you show me in my comment is that I'm just a stupid man, so I may not tell anything! But anyway, the two solutions are good! Maybe it sounds stupid for you, but I do like that, as many developers! And yes, my comment was useful, because it showed an other face of the problem. Even if I couldn't give proofs! But stupidly fighting as we do is not useful... – Vincent Apr 14 '16 at 18:53
  • @vincent I'm not fighting, I'm just asking you to provide more solid arguments. It is not my intention at all to make you feel stupid. I still don't know which problem you're referring to – Ruan Mendes Apr 14 '16 at 21:53
0

You could use a Array#map() and an array for the keys (it is necessary for the right order of the items in the result array).

var array = [{ "userid": "18061997", "fname": "Mike", "bname": "Brouwer", "admin": "2", "email": "", "username": "promike360", "password": "yz", "phone": "06-36505011", "street": "", "streetnumber": "", "zipcode": "", "city": "" }, { "userid": "123456789", "fname": "Anneke", "bname": "van Spaandonk", "admin": "1", "email": "a.vanspaandonk@tele26.nl", "username": "anneke", "password": "xy", "phone": "06-24157017", "street": "Bunschotenstraat", "streetnumber": "14", "zipcode": "5043 BA", "city": "Tilburg" }],
    keys = ["fname", "bname", "email", "username"],
    result = array.map(function (a) {
        return keys.map(function (k) {
            return a[k];
        });
    });

console.log(JSON.stringify(result, 0, 4));
Jed Fox
  • 2,979
  • 5
  • 28
  • 38
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • The problem is that `$.getJSON('http://getapi.promike360.com/json.php')` outputs an object. When i log that object to the console. I can see at `responseText:....` the JSON output. But i don't know how to extract this value. – UNTITLED.PNG Apr 14 '16 at 14:10
  • i get a string with an array inside. maybe you need to parse it first with `JSON.parse()`. – Nina Scholz Apr 14 '16 at 14:16
  • if i do this `console.log($.getJSON('http://getapi.promike360.com/json.php'));` then this will be the output (there is more text but i didn't inculde that shit) `Object {readyState: 1} abort : (a) always : () complete : () promise : (a) readyState : 4 responseJSON : Array[2] responseText : "[{"userid":"18061997","fname":"Mike","bname":"non","admin":"2","email":"","username":"mike","password":"67876e979212214f7c9b9892b4802bde","phone":"06-7984894","street":"","streetnumber":"","zipcode":"","city":""]" setRequestHeader : (a,b) state : "OK" success : () then : () __proto__ : Object` – UNTITLED.PNG Apr 14 '16 at 14:40
  • that is stuff from jquery, i think (i do not use it). so here take `responseJSON` and parse it and have a look what you get. – Nina Scholz Apr 14 '16 at 14:43
  • Thanks, i now have found a way to use ajax to `responseJSON` and if i output `$ajax.responseJSON` i get this in the console: `Array[2] 0 : Object admin : "2" bname : "Brouwer" city : "" email : "" fname : "Mike" password : "non" phone : "06-non" street : "" streetnumber : "" userid : "18061997" username : "promike360" zipcode : "" __proto__ : Object 1 : Object admin : "1" bname : "van non" city : "Tilburg" email : "non" fname : "Anneke" password : "non" phone : "non" street : "Bunschotenstraat" streetnumber : "14" userid : "123456789" username : "anneke" zipcode : "non" __proto__ : Object` – UNTITLED.PNG Apr 14 '16 at 14:58
  • How can i put all that information seperatly into a javascript array? – UNTITLED.PNG Apr 14 '16 at 14:59
  • When i replace the var `array = [{....}]` with `$ajax.responseJSON` i'm getting the error `Uncaught ReferenceError: keys is not defined`. When I `console.log($ajax.responseJSON);` I see `Array[2]` with 2 objects inside. but when i do `console.log(array);` (with the string you typed of the json line) i see `[Object, Object]` is this maybe the problem? and how should i fix that – UNTITLED.PNG Apr 14 '16 at 16:10
  • sorry, you should only replace the part of array. `keys` is necessary for the properties of the object and for the guarantied order. – Nina Scholz Apr 14 '16 at 17:02
  • But the strange thing is, is that I didn't removed/changed that part of your code. And still getting the error. only changed the first row. – UNTITLED.PNG Apr 14 '16 at 19:33
  • `keys is not defined` shows, that you are missing the `key` variable. – Nina Scholz Apr 14 '16 at 19:37
  • I uploaded the `test.html` file to my server so you can take a look for yourself. Maybe that would be easier. [link](http://getapi.promike360.com/test.html) – UNTITLED.PNG Apr 14 '16 at 19:45
  • please add the line `keys = ["fname", "bname", "email", "username"],` – Nina Scholz Apr 14 '16 at 20:03
0

you can ty this

var data = {
  "firstName": "John",
  "lastName": "Smith",
  "isAlive": "true",
  "age": "25"
};
var keys = Object.keys(data);
var arr = keys.map(function(index) {
  return data[index];
});
console.log(arr)
Jed Fox
  • 2,979
  • 5
  • 28
  • 38
elreeda
  • 4,525
  • 2
  • 18
  • 45
  • The problem is that `$.getJSON('http://getapi.promike360.com/json.php')` outputs an object. When i log that object to the console. I can see at `responseText:....` the JSON output. But i don't know how to extract this value. – UNTITLED.PNG Apr 14 '16 at 14:11
-2
var array = JSON.parse(json_array)

it will output an object:

var array = {firstName : 'John',lastName :  'Smith',isAlive :  'true', age : '25'};

And if you want an array with it, simply pass it throug a foreach loop:

var keys = Object.keys(array);
var output = [];
for (var i = 0 ; i < keys.length; i++)
{
    output.push(array[keys[i]]);
}

Then that's it.

Vincent
  • 1,016
  • 6
  • 11
  • That makes an object. They want an array with just the values. – Aurel Bílý Apr 14 '16 at 13:47
  • I think he wants to keep array keys... Anyway, I edited my post with an helper function – Vincent Apr 14 '16 at 13:51
  • @Vincent I now have this: `var array = JSON.parse($.getJSON('http://getapi.promike360.com/json.php')) var keys = Object.keys(array); var output = []; for (var i = 0 ; i < keys.length; i++) { output.push(array[keys[i]]); }` and i'm getting the error: `VM673:1 Uncaught SyntaxError: Unexpected token o(anonymous function) @ test.html:14` – UNTITLED.PNG Apr 14 '16 at 14:25
  • @ProMike360 and what do you have in `$.getJSON('http://getapi.promike360.com/json.php'` ? I think the JSON parsing fails... Do you have any antislashs into the JSON String? – Vincent Apr 14 '16 at 14:27
  • if i do this `console.log($.getJSON('http://getapi.promike360.com/json.php'));` then this will be the output (there is more text but i didn't inculde that shit) `Object {readyState: 1} abort : (a) always : () complete : () promise : (a) readyState : 4 responseJSON : Array[2] responseText : "[{"userid":"18061997","fname":"Mike","bname":"non","admin":"2","email":"","username":"mike","password":"67876e979212214f7c9b9892b4802bde","phone":"06-7984894","street":"","streetnumber":"","zipcode":"","city":""]" setRequestHeader : (a,b) state : "OK" success : () then : () __proto__ : Object` – UNTITLED.PNG Apr 14 '16 at 14:41
  • So simpler than ever! It is not the direct response which you have, but an Object containing the parsed response! You can just get The associative array with `$.getJSON('http://getapi.promike360.com/json.php').responseJSON[0]`, and then convert it to array with `for` loop in my answer – Vincent Apr 14 '16 at 14:44