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]);
}
To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .
Use the Object. values() method to convert an object to an array of objects, e.g. const arr = Object. values(obj) .
toString() method is used to convert: an array of numbers, strings, mixed arrays, arrays of objects, and nested arrays into strings.
Core Java bootcamp program with Hands on practicetoArray() returns an Object[], it can be converted to String array by passing the String[] as parameter.
Try this:
var output = input.map(function(obj) {
return Object.keys(obj).sort().map(function(key) {
return obj[key];
});
});
Converts Array of objects into Array of Arrays:
var outputData = inputData.map( Object.values );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With