Converting JavaScript object with numeric keys into array
Solution 1
It's actually very straight forward with jQuery's $.map
var arr = $.map(obj, function(el) { return el });
and almost as easy without jQuery as well, converting the keys to an array and then mapping back the values with Array.map
var arr = Object.keys(obj).map(function(k) { return obj[k] });
That's assuming it's already parsed as a javascript object, and isn't actually JSON, which is a string format, in that case a run through JSON.parse
would be necessary as well.
In ES2015 there's Object.values
to the rescue, which makes this a breeze
var arr = Object.values(obj);
Solution 2
var json = '{"0":"1","1":"2","2":"3","3":"4"}';
var parsed = JSON.parse(json);
var arr = [];
for (var x in parsed) {
arr.push(parsed[x]);
}
console.log(arr)
Hope this is what you're after!
Solution 3
You simply do it like
var data = {
"0": "1",
"1": "2",
"2": "3",
"3": "4"
};
var arr = [];
for (var prop in data) {
arr.push(data[prop]);
}
console.log(arr);
Solution 4
There is nothing like a "JSON object" - JSON is a serialization notation.
If you want to transform your javascript object to a javascript array, either you write your own loop [which would not be that complex!], or you rely on underscore.js _.toArray()
method:
var obj = {"0":"1","1":"2","2":"3","3":"4"};
var yourArray = _(obj).toArray();
Solution 5
Nothing hard here. Loop over your object elements and assign them to the array
var obj = {"0":"1","1":"2","2":"3","3":"4"};
var arr = [];
for (elem in obj) {
arr.push(obj[elem]);
}
Related videos on Youtube
Nikhil Agrawal
Experienced and Passionate Java developer with a wide range of skill set and wide technology background in both core and advanced java world. I have experience of working with agile methodologies with hands on experience of tools like JIRA and confluence. I have had training and am following secure software development methods. I have been using Secure SDLC in my projects for quite a while. I have handled the requirements from initiation to deployment phase, like requirement gathering and analysis, transforming business requirement into technical requirement, preparing technical designs, developing and testing the module with the help of a development team and deployment. I like to explore and implement new technologies and have implemented new technologies in projects before. I like to read technical news, articles and blogs to keep myself updated. Technology Stack : • Java • Spring Framework • SpringBoot • Microservices • Hibernate • REST Web Services • Javascript, jQuery, HTML • Backbone.js, Marionette.js • Git • JIRA • Salesforce • Jenkins
Updated on July 17, 2022Comments
-
Nikhil Agrawal almost 2 years
I have an object like this coming back as a JSON response from the server:
{ "0": "1", "1": "2", "2": "3", "3": "4" }
I want to convert it into a JavaScript array like this:
["1","2","3","4"]
Is there a best way to do this? Wherever I am reading, people are using complex logic using loops. So are there alternative methods to doing this?
-
BENARD Patrick over 10 yearsduplicate : stackoverflow.com/questions/6857468/…
-
moonwave99 almost 9 yearsA mere loop is no complex logic, by the way : ))
-
-
Nikhil Agrawal over 9 years@adeneo Sir can you please provide some explanation about htis methods.
-
Gopalakrishna Palem over 9 yearsThanks - works like charm. But how to make it do the same for internal objects also (objects within objects)? Internal objects should also become flat members of the array at the root level (so that they can be passed to, say, datatables.net etc.)
-
Dzeimsas Zvirblis almost 9 years@adeneo aka Mr. burns... Thanks for this quick solution.
-
antoine almost 9 years@NikhilAgrawal The trick here is to use Object.keys(), which returns the keys of the object (= its own enumerable properties) as an array. Then we can use array.map to replace each key by the corresponding value in a new array.
-
sheriffderek over 8 yearsThis is an answer, but not a very friendly one.
-
leejt489 over 8 yearsDon't you need to sort the result of Object.keys first? I believe JS does not guarantee any property order.
-
adeneo over 8 years@leejt489 - there is no order in objects, just as there is no order mentioned in the question, it's just a question of how to return the objects values instead of the keys, as an array.
-
adeneo over 8 yearsAnd sorting the keys does not necessarily sort the array of values
-
leejt489 over 8 yearsThe question wasn't explicit, but I had assumed that the keys of the object are indexes of the array by nature of them being (0,1,2,3). Just pointing out that people should know that this method doesn't guarantee any order in the array; if the keys are indexes then you need to explicitly order them so the array is built in the correct order.
-
adeneo over 8 years@leejt489 - maybe you're right, and maybe you're wrong. The OP is asking for a solution on how to get the values from the object into an array, and as there is no order in objects, there is no order in the array either. If the object was something like
{"0":"2", "1":"1", "2":"5", "3":"1"}
, what would you expect the result to be,["2", "1", "5", "1"]
or["1", "1", "2", "5"]
? There's really no expection of order here, it's all just an opinion, and the OP doesn't specify anything other than just getting the values, not the keys. -
amanda fouts over 8 yearsthanks. really needed that. someone used an object as an array throughout a ton of code, which was fine until i needed to build on top of it...
-
HellBaby about 8 yearsYour solution is going to be the slowest one from all presented here... Bad for business code ;)
-
Yasin Patel over 7 years@adeneo ,Thanks
-
Andrew over 7 yearsvery close to what I needed thanks: for(var x in data){ arr[x] = data[x]; }
-
radbyx over 6 years+1: "There is nothing like a "JSON object" - JSON is a serialization notation." - I can't believe how many times I had to hear this before fully understand it.
-
Mogsdad over 6 yearsThank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you've made.
-
Charles Taylor about 4 yearsThe question is about javascript not PHP.
-
riv over 3 yearsIf the server responds with
{"0":"0","2":"2","1":"1"}
and you read it as["0","2","1"]
instead of["0","1","2"]
then it is most certainly a bug, I don't see any ambiguity here. -
informatik-handwerk.de over 2 yearsThe answer is correct only under stronger assumptions than stated in the question. Those proposed solutions will produce an array with indexes starting from 0 and continuously upwards. Hover the actual keys might "just be numeric", start anywhere and contain holes.