且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从Javascript中的对象列表中提取对象属性

更新时间:2023-02-19 09:25:52

这应该有效:

types = _.chain(input) // enable chaining
  .values()            // object to array
  .flatten()           // 2D array to 1D array
  .pluck("type")       // pick one property from each element
  .uniq()              // only the unique values
  .value()             // get an unwrapped array

小提琴: http://jsfiddle.net/NFSfs/

当然,如果您愿意,可以删除所有空格:

Of course, you can remove all whitespace if you want to:

types = _.chain(input).values().flatten().pluck("type").uniq().value()

或不链接:

types = _.uniq(_.pluck(_.flatten(_.values(input)),"type"));






flatten似乎可以处理对象,即使文档明确指出它不应该。如果您希望针对实现进行编码,则可以省略对的调用,但我不建议这样做。实施可能会在一天内发生变化,导致您的代码被神秘地破坏。


flatten seems to work on objects, even though the documentation clearly states it shouldn't. If you wish to code against implementation, you can leave out the call to values, but I don't recommend that. The implementation could change one day, leaving your code mysteriously broken.