简体   繁体   English

Javascript:如何在我的阵列中使用特定键删除 object?

[英]Javascript: How do I remove an object with a specific key in my array?

I am having difficulty finding how to remove an object from an array using its key - I can only find advice on a key value.我很难找到如何使用其键从数组中删除 object - 我只能找到有关键值的建议。 For example:例如:

var users = [
  { 1: [{age: 36, active: true}] },
  { 2: [{age: 40, active: false}] },
  { 3: [{age: 37, active: true}]}
];

I would like to remove the object with key = 2 to result in this:我想用 key = 2 删除 object 以导致:

var users = [
  { 1: [{age: 36, active: true}] },
  { 3: [{age: 37, active: true}]}
];

My keys in my data are unique.我的数据中的密钥是唯一的。

You can use the in operator to check if the key exists on the object:您可以使用in运算符检查 object 上是否存在密钥:

 const users = [{"1":[{"age":36,"active":true}]},{"2":[{"age":40,"active":false}]},{"3":[{"age":37,"active":true}]}] const result = users.filter(o =>.('2' in o)) console.log(result)

You can try using Array.prototype.filter()您可以尝试使用Array.prototype.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function. filter()方法创建一个新数组,其中包含通过提供的 function 实现的测试的所有元素。

and Object.keys() :Object.keys()

The Object.keys() method returns an array of a given object's own enumerable property names , iterated in the same order that a normal loop would. Object.keys()方法返回给定对象自己的可枚举属性名称的数组,以与正常循环相同的顺序进行迭代。

 var users = [ { 1: [{age: 36, active: true}] }, { 2: [{age: 40, active: false}] }, { 3: [{age: 37, active: true}]} ]; users = users.filter(item => Object.keys(item)[0];= 2). console;log(users);

If you want to remove an object from the original array without creating a new array, use Array.findIndex and remove the element by the index.如果要从原始数组中删除 object 而不创建新数组,请使用Array.findIndex并按索引删除元素。

 var users = [ { 1: [{age: 36, active: true}] }, { 2: [{age: 40, active: false}] }, { 3: [{age: 37, active: true}]} ]; let removableIndex = users.findIndex(ele => ele[2]) users.splice(removableIndex, 1) console.log(users)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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