简体   繁体   English

如何从数组中删除对象?

[英]How to remove object from an array?

I have this array which I've had to push the objects into the array. 我有这个数组,我不得不将对象推入数组。 But now I am trying to get rid of the whole object for 'cahlan'. 但是现在,我试图摆脱“卡伦”的整个对象。 The for loop at the bottom is what I've tried but it doesn't seem to work. 底部的for循环是我尝试过的方法,但似乎不起作用。

var employees = [];

var tyler = {
  name: 'Tyler',
  position: 'Lead Instructor/Engineer',
  spiritAnimal: 'Honey Badger'
};

var cahlan = {
  name: 'Cahlan',
  position: 'CEO',
  spiritAnimal: 'butterfly'
};

var ryan = {
  name: 'Ryan',
  position: 'Marketing',
  spiritAnimal: 'fox'
};

var colt = {
  name: 'Colt',
  position: 'Everything really',
  spiritAnimal: 'Young Male Horse'
};

employees.push("tyler", "cahlan", "ryan", "colt");

for (var i = 0; i < employees.length; i++) {
  if (employees[i].name === "Cahlan") {
    employees.splice(i);
  }
}

 var employees = []; employees.push("tyler", "cahlan", "ryan", "colt"); for (var i = 0; i < employees.length; i++) { if (employees[i] === "cahlan") { employees.splice(i, 1); break; } } console.log(employees) 

Two things: 两件事情:

  • You're making a comparison with a Capitalize word Cahlan . 您正在与大写单词Cahlan进行比较。
  • The objects within employees array are Strings, therefore, the attr name doesn't exist. 员工数组中的对象是字符串,因此,attr name不存在。

Probably you didn't realize but you're not adding the objects you've initialized, so, the array is being initialized with Strings. 可能您没有意识到,但没有添加已初始化的对象,因此正在使用Strings初始化数组。

Your solution is heading the right direction but you made two mistakes. 您的解决方案正在朝着正确的方向发展,但您犯了两个错误。

First of all 首先

employees.push("tyler", "cahlan", "ryan", "colt");

does not push your objects in the array as you expect. 不会按预期将对象推入数组。 It pushes strings into employees which only contain the variable names of your objects. 它将字符串推送到仅包含对象变量名的employees中。 JavaScript doesn't know you're trying to refer to those objects. JavaScript不知道您要引用这些对象。 It thinks your just creating some text. 它认为您只是在创建一些文本。 To make it right, remove the double quotes: 为了正确起见,请删除双引号:

employees.push(tyler, cahlan, ryan, colt);

You can always check the content of an array by printing it to the console: 您始终可以通过将其打印到控制台来检查数组的内容:

console.log(employees);

Secondly, you need to pass a second parameter to splice which tells it how many items to remove from the array. 其次,您需要将第二个参数传递给splice ,该参数告诉它要从数组中删除多少个项目。 Since you only want to remove one item, do this: 由于您只想删除一项,因此请执行以下操作:

employees.splice(i, 1);

Full solution: 完整解决方案:

 var employees = []; var tyler = { name: 'Tyler', position: 'Lead Instructor/Engineer', spiritAnimal: 'Honey Badger' }; var cahlan = { name: 'Cahlan', position: 'CEO', spiritAnimal: 'butterfly' }; var ryan = { name: 'Ryan', position: 'Marketing', spiritAnimal: 'fox' }; var colt = { name: 'Colt', position: 'Everything really', spiritAnimal: 'Young Male Horse' }; employees.push(tyler, cahlan, ryan, colt); // 1.) remove double quotes console.log(employees); // print array to console to check if array is setup right for (var i = 0; i < employees.length; i++) { if (employees[i].name === "Cahlan") { employees.splice(i, 1); // 2.) add second paramter } } console.log(employees); // print array again to see if removing worked 

Plain javascript: 普通的javascript:

var ret = [];

for (var i = 0; i < employees.length; i++) {
  if (employees[i].name !== "Cahlan") ret.push(employees[i]);
}

//ret has the employees with Cahlan removed.

Using Jquery: 使用jQuery:

employees = $.grep(employees, function(a)) {
  return a.name !== "Cahlan";
});

And you should do more searching first. 而且,您应该先进行更多搜索。 See remove-object-from-array-using-javascript 请参阅使用JavaScript从数组中删除对象

I just thought I could teach you how to fish first by properly working with objects 我只是以为我可以教你如何通过正确地处理物体来钓鱼

In case you have control over the creation/declaration, just do the right thing and properly construct objects 如果您可以控制创建/声明,只需做正确的事并正确构造对象

var employees = [
{
  name: 'Tyler',
  position: 'Lead Instructor/Engineer',
  spiritAnimal: 'Honey Badger'
 },
{
  name: 'Tyler',
  position: 'Lead Instructor/Engineer',
  spiritAnimal: 'Honey Badger'
},
{
  name: 'Cahlan',
  position: 'CEO',
  spiritAnimal: 'butterfly'
},
{
  name: 'Ryan',
  position: 'Marketing',
  spiritAnimal: 'fox'
},
{
  name: 'Colt',
  position: 'Everything really',
  spiritAnimal: 'Young Male Horse'
}];

If you do not I suggest you concat: 如果您不这样做,我建议您进行合并:

var obj = Object.assign({}, tyler, cahlan, ryan, colt);

which will be equal to the full object above, 等于上面的完整对象,

Now there are several ways of OMITTING object from an ARRAY, some way is delete, skip in the loop as you rightly suggested above. 现在,有几种方法可以从阵列中删除对象,有些方法是删除,如您正确建议的那样,跳过循环。

you can try lodash _.omit, _.concat etc for you troubles 你可以尝试lodash _.omit, _.concat等给你带来麻烦

//1
employees.shift(); // first element removed
//2
employees= employees.slice(1); // first element removed
//3
employees.splice(0,1); // first element removed
//4
employees.pop(); // last element removed
// 5 return everything but Cahlan
employees.filter(function(arr) { return arr.name !== "Cahlan"; }); 
// 5 return only Cahlan
employees.filter(function(arr) { return arr.name === "Cahlan"; }); 

first, use 首先,使用

employees.push(tyler,cahlan,ryan,colt)

without the " " 没有" "

then.... 然后....

employYouWant = employees.filter( (employ) => employ.name === 'Cahlan')///{name: 'Cahlan', position: 'CEO', spiritAnimal: 'butterfly'};

"" is a String, {} is an Object literal ""是字符串, {}是对象文字
therefore employees.push("tyler", "cahlan", "ryan", "colt"); 因此, employees.push("tyler", "cahlan", "ryan", "colt"); is pushing…♪ Strings. 在推…♪弦。

After fixing this to - pushing your actual object literals: 解决此问题后-推送实际的对象文字:

employees.push(tyler, cahlan, ryan, colt);

you have finally access to your Object's .name property. 您终于可以访问对象的.name属性。
Than you can .filter() your array: 比你可以.filter()你的数组:

 var employees = []; var tyler = { name: 'Tyler', position: 'Lead Instructor/Engineer', spiritAnimal: 'Honey Badger' }; var cahlan = { name: 'Cahlan', position: 'CEO', spiritAnimal: 'butterfly' }; var ryan = { name: 'Ryan', position: 'Marketing', spiritAnimal: 'fox' }; var colt = { name: 'Colt', position: 'Everything really', spiritAnimal: 'Young Male Horse' }; employees.push(tyler, cahlan, ryan, colt); // Push your actual Object literals employees = employees.filter( obj => obj.name !== "Cahlan" ); console.log( employees ) 

See this more functional approach to filtering your array. 请参阅此功能更强大的方法来过滤阵列。 The same way you can make helper functions to manage your employees Array: 您可以通过使用助手功能来管理员工数组的方式相同:

 let employees = []; const addEmployee = (name, position, spiritAnimal) => employees.push({name, position, spiritAnimal}); const removeEmployee = (name) => employees = employees.filter( obj => obj.name !== name ); // Let's add some to Array addEmployee('Tyler', 'Lead Instructor/Engineer', 'Honey Badger'); addEmployee('Cahlan', 'CEO', 'butterfly'); addEmployee('Ryan', 'Marketing', 'fox'); addEmployee('Colt', 'Everything really', 'Young Male Horse'); // Let's remove some from Array removeEmployee('Cahlan'); removeEmployee('Colt'); console.log( employees ); 

or you can rewrite the above in a more generic Prototypal or Class -y way and Array agnostic. 或者,您也可以采用更通用的原型Class -y方式重写上述内容,并且与数组无关。

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

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