14

There is a condition where i need to convert Array of objects into Array of Arrays.

Example :-

arrayTest = arrayTest[10 objects inside this array]

single object has multiple properties which I add dynamically so I don't know the property name.

Now I want to convert this Array of objects into Array of Arrays.

P.S. If I know the property name of object then I am able to convert it. But i want to do dynamically.

Example (If I know the property name(firstName and lastName are property name))

var outputData = [];
for(var i = 0; i < inputData.length; i++) {
 var input = inputData[i];
 outputData.push([input.firstName, input.lastName]);
}
Danilo Valente
11.4k8 gold badges55 silver badges71 bronze badges
asked Mar 18, 2014 at 11:11

3 Answers 3

35

Converts Array of objects into Array of Arrays:

var outputData = inputData.map( Object.values );

answered Oct 25, 2016 at 11:36
Sign up to request clarification or add additional context in comments.

1 Comment

Only thing, I had to collect keys from obj and then added using unshift to insert into first position! Otherwise, perfect oneliner!
24

Try this:

var output = input.map(function(obj) {
 return Object.keys(obj).sort().map(function(key) { 
 return obj[key];
 });
});
answered Mar 18, 2014 at 11:14

5 Comments

Thank you Sabof. I got it what i wanted. Actually I am working on a jQuery Datatable so for your help i get the data. Now i need Property name for Datatable columns heading. Can you tell me how i can get single object's property name??
@user3292436 Just use this bit: Object.keys(obj).sort()
hi Sabof. I solved my problem but i couldn't understand the logic behind of MAP method. I have searched on google and found some answer (Its return an array and etc.) but couldn't understand. Can you please explain??
@Mohit map creates a new array, where each item is the result of function applied to an item in the original array
Hi @sabof, is the sort important here? Can I skip it if I don't want to alter the order of my values?
0

Use the for-in loop

var outputData = [];
for (var i in singleObject) {
 // i is the property name
 outputData.push(singleObject[i]);
}
answered Mar 18, 2014 at 11:16

Comments

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.