-5

I really want to convert a object to array but my codes doesn’t worked.

data = "errors": {
  "user": {
    "name": "empty"
  },
  {
    "length": "exceeds"
  },

  "title": {
    "name": "empty"
  },
  {
    "length": "exceeds"
  }
}

Now I want to make them:

data = ["empty", "exceeds", "empty", "exceeds"];

What I’ve done so far is:

var arr = Object.keys(data[i].data.errors).map(function(k) {
  return data[i].data.errors[k]
});

console.log(arr);

But the output is not what I expected. Please help. Thank very much.

Shanoor
  • 13,344
  • 2
  • 29
  • 40
qazzu
  • 361
  • 3
  • 5
  • 16

1 Answers1

1

If you always know the keys of the inner objects are going to be name and length a short way might be:

var out = Object.keys(data.errors).reduce(function (p, c) {
  return p.concat([data.errors[c].name, data.errors[c].length]);
}, []);

DEMO

Andy
  • 61,948
  • 13
  • 68
  • 95