javascript 根据键/值从 JSON 数组中删除条目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10019451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Removing entry(s) from JSON array based on key/value
提问by S16
This is what my object looks like (I don't have a lot of control over how it's formatted):
这就是我的对象的样子(我对它的格式没有太多控制权):
[{
"Country": "Spain",
"info info1": 0.329235716,
"info info2": 0.447683684,
"info info3": 0.447683747
}, {
"Country": "Chile",
"info info1": 1.302673893,
"info info2": 1.357820775,
"info info3": 1.35626442
}, {
"Country": "USA",
"info info1": 7.78805016,
"info info2": 26.59681951,
"info info3": 9.200900779
}]
There will be various countries I need to keep the data for, but change the country name. There will also be countries I need to omit altogether.
我需要保留多个国家/地区的数据,但要更改国家/地区名称。还有一些国家我需要完全省略。
This is one of those times that I've bitten off more than I can chew all at once, and the work I've done so far is just tire spinning.
这是我一次吃不完的时间之一,到目前为止我所做的工作只是轮胎打滑。
$.each(output_json, function() {
$.each(this, function(k, v) {
console.log(k);
});
});
I was attempting to loop through it in this manner, but I'm just getting key/value pairs and I'm not sure how to remove an entire entry based on what I find inside.
我试图以这种方式循环遍历它,但我只是得到键/值对,我不确定如何根据我在里面找到的内容删除整个条目。
Does anyone know of a function/library/jQuery plugin that will quickly allow me to manipulate the object in the manner I've described?
有谁知道一个函数/库/jQuery 插件可以让我以我描述的方式快速操作对象?
回答by Gazler
Underscore.jsis the library to use for all things data. Functions that will be useful for your data are; each, rejectand groupBy.
Underscore.js是用于所有事物数据的库。对您的数据有用的函数是;每个,拒绝和groupBy。
回答by Bergi
Damn, forget about jQuery! This is a pure javascript task.
该死的,忘记 jQuery!这是一个纯 javascript 任务。
- To loop through an Array, use
for (var i=0; i<array.length; i++)
, to loop over an Object usefor (var i in object)
- To delete an array entry, use
splice()
. To delete an object attribute, usedelete object[key];
. - To filter an Array, in modern javascript versions you can use
filter()
with a callback function for every entry; it creates a new Array. There is no such (native) method for objects.
- 要循环遍历数组,请使用
for (var i=0; i<array.length; i++)
, 循环遍历对象使用for (var i in object)
- 要删除数组条目,请使用
splice()
. 要删除对象属性,请使用delete object[key];
。 - 要过滤数组,在现代 javascript 版本中,您可以
filter()
为每个条目使用回调函数;它创建一个新数组。对象没有这样的(本机)方法。
You may find some libraries with helpful utility functions, like underscore. But to learn JS, it may be better to do it with native methods first.
您可能会发现一些具有有用实用功能的库,例如下划线。但是要学习JS,最好先用native方法来做。
回答by Chris Carew
$(output_json).each(function(i){
if (this["Country"] == "USA") output_json.splice(i,1);
else if (this["Country"] == "Spain") this["Country"] = "Brazil";
else {
var country = this;
$(this).each(function(i){
if (this["info info2"] == 1.302673893) {
country.splice(i,1);
}
});
}
})
That's the skeleton of the code - obviously you probably have a better way of detecting renames, removals, etc. But the use of the splice method and the square brackets make this safer than using delete, and more efficient than maintaining multiple arrays, etc.
这是代码的骨架——显然你可能有更好的方法来检测重命名、删除等。 但是使用 splice 方法和方括号使它比使用删除更安全,比维护多个数组等更有效。
回答by Milimetric
I believe the following code does roughly what you're asking for. Check out the working fiddle: http://jsfiddle.net/pUhDR/3/By the way, I agree with @Gazler, you could use the underscore library, it's more high level and easier to read than this:
我相信以下代码大致可以满足您的要求。查看工作小提琴:http: //jsfiddle.net/pUhDR/3/顺便说一句,我同意@Gazler,您可以使用下划线库,它比这更高级且更易于阅读:
var countriesString = JSON.stringify([{
"Country": "Spain",
"info info1": 0.329235716,
"info info2": 0.447683684,
"info info3": 0.447683747
}, {
"Country": "Chile",
"info info1": 1.302673893,
"info info2": 1.357820775,
"info info3": 1.35626442
}, {
"Country": "USA",
"info info1": 7.78805016,
"info info2": 26.59681951,
"info info3": 9.200900779
}]);
var countries = JSON.parse(countriesString);
// create new array
var newCountriesArray = new Array();
// exclude some countries
var excludeCountries = new Object();
excludeCountries['Spain'] = true;
// rename some countries
var renameCountries = new Object();
renameCountries['USA'] = 'United States of America';
for (index in countries) {
if (countries[index].Country in renameCountries) {
countries[index].Country = renameCountries[countries[index].Country];
}
if (!(countries[index].Country in excludeCountries)) {
newCountriesArray.push(countries[index]);
}
}
alert(JSON.stringify(newCountriesArray));
回答by kinakuta
If you don't want to write the code directly to do the operations you want, you can use a library like underscore.jswhich packages up a lot of handy functions for manipulating collections. So after you've parsed your JSON, you could, for example, use reject() to filter out a specific object in your collection.
如果你不想直接编写代码来做你想要的操作,你可以使用像underscore.js这样的库,它打包了很多方便的函数来操作集合。因此,在解析 JSON 之后,您可以使用拒绝() 来过滤掉集合中的特定对象。
回答by Selvakumar Arumugam
You can use delete
operator on the array and delete the element.
您可以delete
在数组上使用运算符并删除元素。
- Create a list of items you wanted to delete. In below case 'Chile'
- Iterate over the list and delete the items
- 创建要删除的项目列表。在下面的情况下'智利'
- 遍历列表并删除项目
Code:
代码:
var toRemove = [];
$.each(output_json, function(i) {
$.each(this, function(k, v) {
if (v == 'Chile') toRemove.push(i);
});
});
//remove all marked
for (var i = 0; i < toRemove.length; i++) {
delete output_json[toRemove[i]];
}