根据属性值过滤对象数组,并从剩余对象中删除一些属性

时间:2017-10-18 18:59:43

标签: javascript

我想从我的数组中删除一个对象的多个项目,任何内置函数都可以帮助我解决我的问题:

数组是:

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}
]

如果输入为1,我想从我的filtere数组中删除 Id 数据,所以我的新数组是:

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

app.html:

基于id删除数组:

**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
}

3 个答案:

答案 0 :(得分:1)

除了filter()之外,您还应该使用map(),如下所示:

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;
          });
}

答案 1 :(得分:1)

可能是地图:

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

请注意,这是一个很酷的新东西(使用rest运算符进行对象解析),但works,至少在现代浏览器上......

答案 2 :(得分:0)

使用map功能:

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