通过键删除数组中的对象

时间:2019-12-16 09:28:53

标签: javascript

我正在尝试通过JavaScript中的键删除对象

这是数组的例子

{
Account Manager: {selected: true}
Arrival: {selected: true}
Client: {selected: true}
Client Contact: {selected: true}
Created: {selected: true}
Created by: {selected: true}
Departure: {selected: true}
Destination: {selected: true}
Keywords: {selected: true}
Status: {selected: true}
}

现在我正在尝试从此阵列中删除状态和客户端,但是我不知道该如何做。 我已经尝试过了:

for(var i=0; i<list.length; i++) {
    if(list[i] == 'Status' || list[i] == 'Client') {
       list.splice(i, 1);
    }
}

3 个答案:

答案 0 :(得分:2)

提供的示例是Object,而不是array。由于您使用的是AngularJS,因此可以直接使用JavaScript从对象中删除密钥。

下面是仅使用delete()方法的示例

 const _object = {
      "Account Manager": { selected: true },
      "Arrival": { selected: true },
      "Client": { selected: true },
      "Client Contact": { selected: true },
      "Created": { selected: true },
      "Created by": { selected: true },
      "Departure": { selected: true },
      "Destination": { selected: true },
      "Keywords": { selected: true },
      "Status": { selected: true }
    }

    delete _object["Status"];

    console.log(_object);

答案 1 :(得分:0)

我们可以使用reduce函数-

let newList = Object.keys(oldList).reduce((acc, key) => {
    if(key !== 'Status' || key !== 'Client'){
        acc[key] = oldList[key]
    }
    return acc;
}, {})

答案 2 :(得分:0)

我们可以使用delete密钥--

delete object["keyName"];

这将删除该特定键...