-2

I have an object like

obj = {
   a0: 1,
   b0: 2,
   b1: 3,
   a1: 4
}

I want make this object to array as shown

obj1 = [
       {a0: 1, b0: 2},
       {a1: 4, b1: 3}
]

Group properties that end with same number. Please help me

Mr_Perfect
  • 8,254
  • 11
  • 35
  • 62

1 Answers1

3

You could use the number of the key as index and build a new object, if not exist. Then apply the value to the property.

var object = { a0: 1, b1: 3, a1: 4, c2: 5 },
    grouped = Object.keys(object).reduce(function (result, key) {
        var index = key.match(/\d+$/);
        result[index] = result[index] || {};
        result[index][key] = object[key];
        return result;
    }, []);

console.log(grouped);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392