使用 Underscore Map 获取对象的前 N ​​个属性

Get the first N properties of an Object using Underscore Map

我有一个对象,想使用下划线(map/each 任何东西)获取前 n 个项目

代码如下:

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

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

输出应该像 [{a:1}, {b:2}...]

纯ES6方案,无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}]

但是你也应该知道 Object.keys 不保证特定的顺序。它 returns 一个对象的键数组,按照将属性原始插入该对象的顺序排列。最后一个可能取决于 JavaScript 引擎实现,因此如果顺序真的很重要,最好使用数组。

您可以使用 keys and first and then use pick 获取前 2 个键的名称以获取这些键:

let result = _.pick(input, _.first(_.keys(input), 2 ))