在javascript / jquery中从JSON中删除元素 [英] Deleting an element from JSON in javascript/jquery

查看:97
本文介绍了在javascript / jquery中从JSON中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在javascript中从JSON对象中删除数据时遇到问题。我正在动态创建这个JSON,并且还应该动态地进行删除。以下是我的JSON和我所处的情况。

I have a problem in deleting data from a JSON object in javascript. I'm creating this JSON dynamically and the removal shall also take place dynamically. Below is my JSON and the situation I'm in to.

    {brands:[51,2046,53,67,64]}

现在,我必须从中删除53,我使用一些elements属性计算,但是我无法删除数据,无法找到解决此问题的方法。请帮帮我,谢谢。

Now, I have to remove 53 from this which I am calculating using some elements property, but I'm not able to remove the data and unable to find the solution for this situation. Please help me folks, thank you.

推荐答案

尝试使用 Array.prototyp.splice

var data = { brands:[51,2046,53,67,64] };
data.brands.splice(2,1);

因为您要从中删除元素一个简单的对象中的数组。并且 splice 将返回已删除元素的数组。

Since you want to remove an element from an array inside of a simple object. And splice will return an array of removed elements.

如果你不知道要删除的元素的位置,那么使用 .indexOf()来找到动态元素的索引,

If you do not know the position of the element going to be removed, then use .indexOf() to find the index of the dynamic element,

var elementTobeRemoved = 53;
var data = { brands:[51,2046,53,67,64] };
var target = data.brands;
target.splice(target.indexOf(elementTobeRemoved),1);

您可以编写与下面这样的函数相同的东西,

You could write the same thing as a function like below,

function removeItem(arr,element){
 return arr.splice(arr.indexOf(element),1);
}

var data = { brands:[51,2046,53,67,64] };
var removed = removeItem(data.brands,53);

这篇关于在javascript / jquery中从JSON中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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