The following javascript is intended to take an array of objects, search for a property on each one, specified by an array of property names, and use underscore.js to to select items from the array that are unique in that aspect. For some reason, however, it returns an array with only a single object: [{type: {sub: 'a'}}]

Does anyone know why? (Using Chrome Version 34.0.1847.131 m, if you care.)

Thanks.

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);
有帮助吗?

解决方案

a typo! you're using brackets instead of parentheses when doing hasOwnProperty check.

if(!result.hasOwnProperty(objectID[i]))

also, you haven't to add the array when calling _uniq since you're already chaining it:

 _.chain(array)
        .uniq(function(item, key) {
            return getFromObjectID(item);
        })
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top