-1

Suppose I have an object with 10 key values,

const detail = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10}

I only want to get first 5 key values from object,

**{'a':1,'b':2,'c':3,'d':4,'e':5}**

Like we can slice in array and get first 5 elements, is it possible to do something for the same.

I tried looking for solution, but was unable to find anything related to it.

Any help would really be helpful. If anyone needs any moew details please let me know.

Siva Pradhan
  • 791
  • 1
  • 6
  • 23

2 Answers2

4

You can get an array of the object's entries (key-value pairs in the form of an array), then slice that array and turn it back into an object:

const detail = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10};

const sliced = Object.fromEntries(
  Object.entries(detail).slice(0, 5)
);
console.log(sliced);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • It does work, however, it should be mentioned, that [`Object.entries` has a defined order only since ES2020, and even since it relies on the insertion order only in case of non-index properties](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order), that might cause problems. – FZs Apr 22 '21 at 09:11
  • @FZs The specification [prefers backwards compatibility](https://stackoverflow.com/a/55934491) above all else. The reason it was deemed safe to add this to the specification is because every implementation in use had, at the time, and for many years previously, already had been using that behavior. So I think it's safe to use. – CertainPerformance Apr 22 '21 at 13:09
  • @CertainPerformance I agree, that's why I wrote "it does work", just wanted to mention it, as relying on unspecified things might yield unexpected results, so it might cause problems. In that case, I think, it's better to know such things beforehand. – FZs Apr 22 '21 at 18:14
0

Use Object.fromEntires with Object.entries

Object.entries will return a nested array of key, value pairs, which you can slice and then pass that slice to Object.fromEntries which will return an object.

const detail = { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10 };

const res = Object.fromEntries(Object.entries(detail).slice(0, 5));

console.log(res);
Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28
  • 1
    It does work, however, it should be mentioned, that [`Object.entries` has a defined order only since ES2020, and even since it relies on the insertion order only in case of non-index properties](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order), that might cause problems. – FZs Apr 22 '21 at 09:12