简体   繁体   中英

Removing objects from array based on two properties

I have an array that contains custom objects that look like this:

{
    field: fieldName,
    dataType: usuallyAString,
    title: titleForLocalization,
    environmentLabel: environmentName
}

There are a couple of other properties on the object, but the only ones that I actually care about are field and environmentLabel . I need to filter out any objects that have identical field and environmentLabel but don't care about any other properties. The array can have objects that share field or environmentLabel , just not both.

Ideally I'd like to use Array.filter but have yet to figure out how to do it based on two properties. Also, I am limited to es5.

Create another object that contains all the combinations of properties you want to test. Use filter() and test whether the pair already exists in the object. If not, add the properties to the other object and return true .

var seen = {};
newArray = array.filter(function(obj) {
    if (seen[obj.field]) {
        if (seen[obj.field].includes(obj.environmentLabel) {
            return false;
        } else {
            seen[obj.field].push(obj.environmentLabel);
        }
    } else {
        seen[obj.field] = [obj.environmentLabel];
    }
    return true;
});

 const data = [{ field: 1, dataType: "usuallyAString", title: "titleForLocalization", environmentLabel: 1 }, { field: 1, dataType: "usuallyAString", title: "titleForLocalization", environmentLabel: 1 }, { field: 2, dataType: "usuallyAString", title: "titleForLocalization", environmentLabel: 2 }] var result = _.uniqWith(data, function(arrVal, othVal) { return arrVal.field=== othVal.field && arrVal.environmentLabel=== othVal.environmentLabel; }); console.log(result) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script> 

If you are able to use lodash, you can do:

var result = _.uniqWith(data, function(arrVal, othVal) {
  return arrVal.field=== othVal.field && arrVal.environmentLabel=== othVal.environmentLabel;
});

console.log(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM