Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Array of Objects into Array of Arrays

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]);
}
like image 889
KiddoDeveloper Avatar asked Mar 18 '14 11:03

KiddoDeveloper


People also ask

How do you convert an array of objects to an array?

To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .

How do you turn an object into an array of objects?

Use the Object. values() method to convert an object to an array of objects, e.g. const arr = Object. values(obj) .

Which method is used to convert nested arrays to objects?

toString() method is used to convert: an array of numbers, strings, mixed arrays, arrays of objects, and nested arrays into strings.

Can we convert object to array in Java?

Core Java bootcamp program with Hands on practicetoArray() returns an Object[], it can be converted to String array by passing the String[] as parameter.


2 Answers

Try this:

var output = input.map(function(obj) {
  return Object.keys(obj).sort().map(function(key) { 
    return obj[key];
  });
});
like image 156
sabof Avatar answered Sep 18 '22 01:09

sabof


Converts Array of objects into Array of Arrays:

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

like image 22
Alex Avatar answered Sep 20 '22 01:09

Alex