-4

Please I am trying to convert this object returned from my Web API:

[
    {"a":65,"b":59,"c":80,"d":81,"e":56,"f":55,"g":40},
    {"a":28,"b":48,"c":40,"d":19,"e":86,"f":27,"g":90}
]

Into array of this format inside AngularJS Controller:

[
    [65, 59, 80, 81, 56, 55, 40],
    [28, 48, 40, 19, 86, 27, 90]
]

I researched extensively & applied multiple approaches e.g. using:

  1. var arr = $.map(o, function(el) { return el; })
  2. var arr = Object.keys(o).map(function(k) { return o[k] });
  3. var obj = JSON.parse(json);
  4. Object.keys(obj).forEach(function (key) { arr[key] = obj[key] });

But none of the above worked as all I got from console.log was:

[object Object],[object Object]

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Better Tomorrow
  • 65
  • 2
  • 11
  • Looks easy enough. [array.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map?v=example) + [Object.values](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values) – Kevin B May 18 '17 at 18:56
  • One thing to note is that there's no order to the properties of an object. So the arrays may have the properties in any order. – Barmar May 18 '17 at 19:27
  • @Barmar eh, well, that isn't entirely true anymore. I still wouldn't trust the order presented unless i controlled the creation of the object, but the order is specified now. – Kevin B May 18 '17 at 19:29
  • @KevinB Did ES6 add order to objects? Can you provide a reference? – Barmar May 18 '17 at 19:31
  • @Barmar well, it's a bit... undefined. It's not specified in the spec yet that I know of, but all modern browsers will give you object keys in insertion order with the exception of object keys that are integer-like. Integer-like keys in some browsers will be ordered in ascending order. Here's a somewhat related chrome bug report: https://bugs.chromium.org/p/v8/issues/detail?id=164 – Kevin B May 18 '17 at 19:39

2 Answers2

-1

Try that way

[{"a":65,"b":59,"c":80,"d":81,"e":56,"f":55,"g":40}, 
{"a":28,"b":48,"c":40,"d":19,"e":86,"f":27,"g":90}
].map(function(n) { 
   return Object.keys(n).map(function(nn) { return n[nn] });
});
Yordan Nikolov
  • 2,598
  • 13
  • 16
-1

This should work with any array of key/value objects.

function convert(data) {
  let res = [];
  for (var i = 0; i < data.length; i++) {
    let keys = Object.keys(data[i]);
    let temp = [];
    for (var j = 0; j < keys.length; j++) {
      temp.push(data[i][keys[j]]);
    }
    res.push(temp);
  }
  return res;
}

var json = [
    {"a":65,"b":59,"c":80,"d":81,"e":56,"f":55,"g":40},
    {"a":28,"b":48,"c":40,"d":19,"e":86,"f":27,"g":90}
];



console.log(convert(json));
JellyKid
  • 302
  • 1
  • 6