Kumail Hussain
Kumail Hussain

Reputation: 879

Filter array of objects based on property value, and remove some properties from remaining objects

I want to remove multiple items of an object from my array any built in function can help me to solve my problem :

Array is :

this.array= [ 
    { "Id": 1, "Title": "3 man crew –Distribution", "checked": true,'data': 123},
    { "Id": 2, "Title": "3 man crew – Transmission" ,'data': 123}, 
    { "Id": 3, "Title": "Flagger",'data': 124 },
    { "Id": 1, "Title": "Mowing Crew" ,'data': 183}
    { "Id": 7, "Title": "Mowing Crew3" ,'data': 187}
]

I want to remove Id and Data from my filtere array if input is 1 so my new array is:

[ 
    { "Title": "3 man crew –Distribution", "checked": true},
    { "Title": "Mowing Crew" ,'data': 183} 
]

app.html:

based on the id delete the array :

**app.ts**

deleteCheck(value) {
    //logic to delete id and data 
    this.array = this.array.filter(item => item.Id=== value);
    // returns array but with Id and but i want my new array without data and id
}

Upvotes: 0

Views: 4599

Answers (3)

Andrei
Andrei

Reputation: 44610

Use map function:

var newArray = array
    .filter(item => item.Id === value)
    .map(item => ({ 
        Title: item.Title, 
        checked: item.checked 
    }));

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138367

Probably map:

.map( ({Id, data, ...rest}) => rest);

Note that this is quite new cool stuff ( object destructuring with an rest operator), but it works , at least on modern browsers...

Upvotes: 1

Tudor Ciotlos
Tudor Ciotlos

Reputation: 1845

In addition to filter(), you should also use map(), like this:

deleteCheck(value) {

//logic to delete id and data 
    this.array = this.array.filter(item => item.Id === value)
          .map(item => {
              delete item.Id;
              delete item.Title;
              return item;
          });
}

Upvotes: 1

Related Questions