以下 JavaScript 旨在获取对象数组,搜索每个对象的属性(由属性名称数组指定),并使用 underscore.js 从数组中选择在该方面唯一的项目。然而,由于某种原因,它返回一个仅包含单个对象的数组:[{type: {sub: 'a'}}]
有人知道为什么吗? (如果您关心的话,请使用 Chrome 版本 34.0.1847.131 m。)
谢谢。
var objectID = ["type", "sub"];
var getFromObjectID = function(obj) {
var result = obj;
for(var i = 0; i < objectID.length; i++) {
if(!result.hasOwnProperty[objectID[i]])
return null;
result = result[objectID[i]];
}
return result;
}
var array = [
{type: {sub: "a"}},
{type: {sub: "a"}},
{type: {sub: "b"}},
{type: {sub: "c"}},
{type: {sub: "b"}},
{type: {sub: "a"}},
{type: {sub: "b"}},
{type: {sub: "c"}},
{type: {sub: "a"}},
{type: {sub: "b"}},
{type: {sub: "b"}},
];
var uniqueArray = _.chain(array)
.uniq(array, function(item, key) {
return getFromObjectID(item);
})
.value();
console.log(uniqueArray);
最佳答案
打错字了!在进行 hasOwnProperty
检查时,您使用方括号而不是圆括号。
if(!result.hasOwnProperty(objectID[i]))
此外,在调用 _uniq
时您不必添加数组,因为您已经链接了它:
_.chain(array)
.uniq(function(item, key) {
return getFromObjectID(item);
})
关于javascript - Underscore.js 基于属性名称数组的唯一选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23584813/