根据值从JSON对象中删除元素

时间:2018-01-15 22:43:25

标签: javascript json

我有一个看起来像这样的JSON文件:

{
    "2018-1-15 22:35:22": {
        "entry": "1234",
        "ticket": "32432432432523",
        "name": "test"
    },

    "2018-1-15 23:35:22": {
        "entry": "5678",
        "ticket": "2485181851981",
        "name": "test2"
    }

}

我有这个代码检查JSON文件中是否有一个条目值:

const jsondata = require('./path/to/data.json');

function _isContains(json, value) {
    let contains = false;
    Object.keys(json).some(key => {
        contains = typeof json[key] === 'object' ? _isContains(json[key], value) : json[key] === value;
        return contains;
    });
    return contains;
}

var entryToDelete = 1234
if (_isContains(jsondata, entryToDelete) == true) {
    //delete the entire {} for the entryToDelete 
}

基本上我想删除该元素,如果该条目已存在于JSON文件中。因此,删除元素后,JSON文件应如下所示:

{
    "2018-1-15 23:35:22": {
        "entry": "5678",
        "ticket": "2485181851981",
        "name": "test2"
    }   

}

我尝试使用delete jsondata[entryToDelete];,但这并未删除该元素。

有人可以帮我解决这个问题。 谢谢,

3 个答案:

答案 0 :(得分:1)



const jsondata = {
    "2018-1-15 22:35:22": {
        "entry": "1234",
        "ticket": "32432432432523",
        "name": "test"
    },

    "2018-1-15 23:35:22": {
        "entry": "5678",
        "ticket": "2485181851981",
        "name": "test2"
    }

}

function getKeyFromValue(json, value) {
    let output = null; // assume we don't find the entry
    Object.keys(json).some(key => {
      // if entry is equal to value, then set output to key
      if ( json[key].entry === value ) output=key;
      // return output. As long as it is null, it will continue to with next entry.
      return output;
    });
    return output; // returns the key
}

var entryToDelete = "1234"
var key = getKeyFromValue(jsondata, entryToDelete);
console.log('key', key);
// if the key is set (no need to test for not null)
if (key) delete jsondata[key];
console.log(jsondata);




答案 1 :(得分:0)

这是您的脚本被修改为按预期工作:

var jsonData = {
    "2018-1-15 22:35:22": {
        "entry": "1234",
        "ticket": "32432432432523",
        "name": "test"
    },

    "2018-1-15 23:35:22": {
        "entry": "5678",
        "ticket": "2485181851981",
        "name": "test2"
    }

}

function _isContains(json, value) {
    let contains = false;
    Object.keys(json).some(key => {
        contains = typeof json[key] === 'object' ? _isContains(json[key], value) : json[key] === value;
        return contains = key;
    });
    return contains;
}

var entryToDelete = 1234
var contains = _isContains(jsonData, entryToDelete)

if ( contains !== false) {
    delete jsonData[contains]
    console.log(jsonData)
}

答案 2 :(得分:0)

这就是你所需要的!

var entryToDelete = 1234
for (var key in jsondata) {
    if (jsondata.hasOwnProperty(key) && jsondata[key].entry == entryToDelete) {
        delete jsondata[key];
    }
}