Converting Array of Objects into Array of Arrays

2020-02-28 15:00发布

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]);
}

3条回答
家丑人穷心不美
2楼-- · 2020-02-28 15:27

Use the for-in loop

var outputData = [];
for (var i in singleObject) {
    // i is the property name
    outputData.push(singleObject[i]);
}
查看更多
beautiful°
3楼-- · 2020-02-28 15:35

Try this:

var output = input.map(function(obj) {
  return Object.keys(obj).sort().map(function(key) { 
    return obj[key];
  });
});
查看更多
趁早两清
4楼-- · 2020-02-28 15:45

Converts Array of objects into Array of Arrays:

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

查看更多
登录 后发表回答