user6474292 user6474292 - 4 months ago 7
Javascript Question

How to convert object into array

I have array of object and I want to change into array an remove object.
My object is like

[{STU: "Study1", SUB: 2, EXL: "Yes"}, {STU: "Study2", SUB: 1, EXL: "Yes"}]

and I want result like array with index
[{"Study1",2,"Yes"},{Study2",2,"Yes}]

Answer

Use Array#map over Object.keys(obj)

The Object.keys() method returns an array of a given object's own enumerable properties.

The map() method creates a new array with the results of calling a provided function on every element in this array.

var ip = {
  STU: "Study1",
  SUB: 2,
  EXL: "Yes"
};
var op = Object.keys(ip).map(function(key) {
  return ip[key];
});
console.log(op);

To iterate Array-of-Objects

var ip = [{
  STU: "Study1",
  SUB: 2,
  EXL: "Yes"
}, {
  STU: "Study2",
  SUB: 4,
  EXL: "No"
}];
var op = ip.map(function(item) {
  return Object.keys(item).map(function(key) {
    return item[key];
  });
});

console.log(op);

Comments