从使用JavaScript数组中删除对象 [英] Remove Object from Array using JavaScript

查看:116
本文介绍了从使用JavaScript数组中删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能从数组中删除一个对象?
我希望删除,其中包括名为克里斯蒂安从的someArray的对象。例如:

  =的someArray [{名:克里斯蒂安台词:2,5,10},
             {名字:约翰,台词:1,19,26,96}];

我想实现:

  =的someArray [{名字:约翰,台词:1,19,26,96}];


解决方案

您可以使用多种方法从中取出一个项目:

  // 1
someArray.shift(); //第一个元素中删除
// 2
的someArray = someArray.slice(1); //第一个元素中删除
// 3
someArray.splice(0,1); //第一个元素中删除
// 4
someArray.pop(); //删除最后一个元素

如果您想在的位置删除元素 X ,使用:

  someArray.splice(X,1);

回复 @ chill182 的评论:你可以使用从数组中删除一个或多个元素 Array.filter (见<一href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\">MDN),例如。

\r
\r

=的someArray [{名:克里斯蒂安台词:2,5, 10},\r
             {名字:约翰,台词:1,19,26,96},\r
             {名:布莱恩,台词:3,9,62,36}];\r
johnRemoved =的someArray\r
                .filter(功能(EL){\r
                      返回el.name ==约翰!;\r
                 }\r
);\r
\r
document.querySelector('#结果')的textContent = JSON.stringify(johnRemoved,空,'');

\r

&LT; pre ID =结果&GT;&LT; / pre&GT;

\r

\r
\r

How can I remove an object from an array? I wish to remove the object that includes name "Kristian" from "someArray". For example:

someArray = [{name:"Kristian", lines:"2,5,10"},
             {name:"John", lines:"1,19,26,96"}];

I want to achieve:

someArray = [{name:"John", lines:"1,19,26,96"}];

解决方案

You can use several methods to remove an item from it:

//1
someArray.shift(); // first element removed
//2
someArray = someArray.slice(1); // first element removed
//3
someArray.splice(0,1); // first element removed
//4
someArray.pop(); // last element removed

If you want to remove element at position x, use:

someArray.splice(x,1);

Reply to the comment of @chill182: you can remove one ore more elements from an array using Array.filter (see MDN), e.g.

someArray = [{name:"Kristian", lines:"2,5,10"},
             {name:"John", lines:"1,19,26,96"},
             {name:"Brian",lines:"3,9,62,36" }];
johnRemoved = someArray
                .filter(function (el) {
                      return el.name !== "John";
                 }
);

document.querySelector('#result').textContent = JSON.stringify(johnRemoved, null, ' ');

<pre id="result"></pre>

这篇关于从使用JavaScript数组中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆