vitozev vitozev - 7 months ago 13
Javascript Question

How to accomplish splice-like functionality over objects?

I have the following object:

var data = {
'M.13-17': 0, 'M.18-24': 0, 'M.25-34': 0, 'M.35-44': 0, 'M.45-54': 0, 'M.55-64': 0, 'M.65+': 0,
'F.13-17': 0, 'F.18-24': 0, 'F.25-34': 0, 'F.35-44': 0, 'F.45-54': 0, 'F.55-64': 0, 'F.65+': 0,
};


I want to be able to:


  1. Get first (let's say 5) properties of that object.

  2. Get N properties of that object by passing
    start
    offset.



Currently, I have worked solution where names of object properties are implicitly specified, but I'm looking for more elegant solution.

Answer

You can't, because objects do not guarantee the order of their properties (until certain cases in ES6).

If you want stable indexes, you should use an array of key-value pairs:

var data = [{
  key: 'M.13-17', value: 0
}, {
  key: 'M.18-24', value: 0
}];

var firstFive = data.sort(function (it) { return it.key; }).splice(0, 5);
console.log(firstFive);
Comments