我从 API 接收到以下对象:
{
'2012-12-12': [
{ 'id': 1234,
'type': 'A' },
{ 'id': 1235,
'type': 'A' },
{ 'id': 1236,
'type': 'B' },
],
'2012-12-13': [
{ 'id': 1237,
'type': 'A' },
{ 'id': 1238,
'type': 'C' },
{ 'id': 1239,
'type': 'B' },
]
}
然后我想要另一个名为 types
的 Array
变量,它将保存每个元素的 type
属性的所有可能值对象。在这种情况下,它将是:
types = ['A', 'B', 'C']
我试图以一种功能性的方式完成它(我正在使用 underscore.js),但我无法找到一种方法来完成它。现在我正在使用
types = [];
_.each(response, function(arr1, key1) {
_.each(arr1, function(arr2, key2) {
types.push(arr2.type);
});
});
types = _.uniq(types);
但这非常丑陋。你能帮我想出更好的方法来编写这段代码吗?
谢谢!
最佳答案
这应该有效:
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
fiddle :http://jsfiddle.net/NFSfs/
当然,如果您愿意,您可以删除所有空格:
types = _.chain(input).values().flatten().pluck("type").uniq().value()
或者没有链接:
types = _.uniq(_.pluck(_.flatten(_.values(input)),"type"));
flatten seems to work on objects , 即使 the documentation clearly states it shouldn't .如果您希望针对实现进行编码,您可以省略对 values
的调用,但我不建议这样做。实现可能有一天会发生变化,让您的代码神秘地崩溃。
关于javascript - 从 Javascript 中的对象列表中提取对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14842282/