-1

I have an object and would like to get the first n items using underscore (map/each anything)

Below is the code:

var input = {
  a:1,
  b:2,
  c:3,
  d:4
}

_.map(input, function (value, key, index) {
  if(index < 2) {
    console.log(key + ' == ' + value)
  }
});

Output should be like like [{a:1}, {b:2}...]

dhilt
  • 13,532
  • 6
  • 48
  • 67
prgrmr
  • 772
  • 2
  • 9
  • 28
  • 2
    Properties in an object are not ordered. So talking about the first `n` properties doesn't make much sense. While you can get `n` properties from an object, it is not guaranteed that you get them in the order they are defined. – Felix Kling Oct 19 '17 at 21:59

2 Answers2

1

Pure ES6 solution, with no Underscore/Lodash:

const cutObject = (obj, max) => Object.keys(obj)
  .filter((key, index) => index < max)
  .map(key => ({[key]: obj[key]}));

console.log(cutObject({a:1, b:2, c:3, d:4, e:5}, 3)); // [{a:1}, {b:2}, {c:3}]

But also you should know that Object.keys does not guarantee the particular order. It returns an array of keys of an object in order of original insertion of the properties into that object. This last may depends on JavaScript engine implementation, so it's preferred to use arrays if the order is really important.

marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388
dhilt
  • 13,532
  • 6
  • 48
  • 67
  • Actually I want something like [{a:1}, {b:2}...] – prgrmr Oct 19 '17 at 21:57
  • *"It returns an array of keys of an object in order of original insertion of the properties into that object"* That's not true: `Object.keys({foo: 'bar', 42: 21})`. – Felix Kling Oct 19 '17 at 22:32
  • @FelixKling Yes, it needs to be clarified. Per [MDN-1](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys): "The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop". Per [MDN-2](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in): "The for...in statement iterates over the enumerable properties of an object, in original insertion order." **Something's not okey with 42.** E.g. if I add `aFoo` property manually, then it will be last. – dhilt Oct 19 '17 at 22:39
  • The order in which `for...in` iterates over properties is actually implementation dependent. However, *many* implementations (browsers in particular) will first iterate over numeric properties in ascending order and then over non-numeric properties in insertion order. – Felix Kling Oct 19 '17 at 22:41
  • Thanks! I added an additional warning to the answer. – dhilt Oct 19 '17 at 22:59
1

You could get the names of the first 2 keys using keys and first and then use pick to get those keys:

let result = _.pick(input, _.first(_.keys(input), 2 ))
Gruff Bunny
  • 26,318
  • 10
  • 66
  • 56