根据键/值从JSON数组中删除条目 [英] Removing entry(s) from JSON array based on key/value

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

问题描述

这是我的对象的样子(我对其格式没有太多控制权):

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.

有人知道一个函数/库/jQuery插件,该插件可以快速允许我以我所描述的方式操作对象吗?

Does anyone know of a function/library/jQuery plugin that will quickly allow me to manipulate the object in the manner I've described?

推荐答案

$(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);
            } 
        });
    }
})

这就是代码的骨架-显然,您可能有更好的方法来检测重命名,删除等.但是使用splice方法和方括号比使用delete更加安全,并且比维护多个数组更有效等

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.

这篇关于根据键/值从JSON数组中删除条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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