动态删除复杂JSON数据中的空键(使用vanilla JavaScript)

时间:2018-05-23 17:14:52

标签: javascript json

我尝试了很多不同的方法,只使用JavaScript从JSON文件中动态解析和删除空值。

截至目前,我已经能够删除未嵌套的密钥,但长度大于0的空字符串除外。

我的主要问题是如何访问子值,评估嵌套密钥和仅删除嵌套密钥 - 现在我最终删除了根密钥。

请原谅,如果这是一个重复的问题,但我找不到任何适用于这个或其他地方的特定案例的实施。

这是我到目前为止所做的:



//DATA
let input = '{"first_name": "","last_name": "Smith","email":"jane.smith@wyng.com","gender": null,"invitations": [{"from": "test","code": ""}],"company": {"name": "dds","industries": [""]},"address": {"city": "New York","state": "NY","zip": "10011","street": " "},"new Value": ""}';



//MAIN FUNCTION
function removeEmptyFields(inputJSON) {
  let data = JSON.parse(inputJSON);

  //accessing top level keys (case1)
  for (let key in data) {
    let item = data[key];
    //dig deeper if value not at top level

    if (item !== null && typeof item !== 'object') {

      deleteRecord(item)
    } else {
      lookDeeper(item)
    }

    if (item === null && typeof item === 'object') {
      deleteRecord(item)
    }



    //function that deletes empty records
    function deleteRecord(item) {
      // console.log(item + "#");//function that deletes empty records
      if (item === null || item === undefined ||
        item.length === 0) {

        delete data[key];
      }

    }

    //function to access values nested one level (case2)

    function lookDeeper(key) {

      if (typeof key === 'object' && typeof key != null) {
        for (let key2 in key) {
          if (typeof key[key2] === 'object' && typeof key[key2] != null) {
            console.log()
            for (let subItem in key[key2]) {
              // deleteRecord(key2[subItem])
            }
          }
          deleteRecord(item[key2])
          lookDeeper(item[key2]);
        }
      }
    }
  }
  return data;
}

let output = removeEmptyFields(input)
console.log(output);

//CASES:
//1-> flat object:
//data[key]
//2 -> array/object
//data[key][array-index]
//3 ->object/object
//data[key][subkey]
//4 ->object/object/array
//data[key][subkey][array-index]


// Test cases in order, and delete nulls at the very end. return data as result




3 个答案:

答案 0 :(得分:2)

你实际上非常接近,如果你修复了递归调用并删除了你最终得到的所有必要条件:

function cleanUp(obj) {
  for(const key in obj) {
    const value = obj[key];
    if(typeof value === "object") {
      cleanUp(value);
    } else if(!value && value !== 0) {
      delete obj[key];
    }
  }
}

let output = JSON.parse(input);
cleanUp(output);

答案 1 :(得分:0)

找到了一种方法。 感谢所有贡献的人:

//DATA
let input = '{"first_name": "","last_name": "Smith","email":"jane.smith@wyng.com","gender": null,"invitations": [{"from": "test","code": ""}],"company": {"name": "dds","industries": [""]},"address": {"city": "New York","state": "NY","zip": "10011","street": " "},"new Value": ""}';




function isEmpty(value) {
    if (value === null)
        return true;

    if (typeof value == 'object' && Object.keys(value).length === 0)
        return true;

    if (typeof value == 'string' && value.trim() == '')
        return true;

    return false;
}

function removeEmptyFields(input) {
    if (Array.isArray(input)) {
        for (var index = input.length - 1; index >= 0; index--) {
            if (typeof input[index] == 'object') {
                removeEmptyFields(input[index]);
            }
            if (isEmpty(input[index])) {
                input.splice(index, 1);
            }
        }
    } else {
        for (var index in input) {
            if (typeof input[index] == 'object') {
                removeEmptyFields(input[index]);
            }
            if (isEmpty(input[index])) {
                delete input[index];
            }

        }

    }
    return input
}

答案 2 :(得分:0)

let input = '{"first_name": "","last_name": "Smith","email":"jane.smith@wyng.com","gender": null,"invitations": [{"from": "test","code": ""}],"company": {"name": "dds","industries": [""]},"address": {"city": "New York","state": "NY","zip": "10011","street": " "},"new Value": ""}'

let objTest = JSON.parse( input )

console.dir( objTest )
purge( objTest )
console.dir( objTest )

/* purge recursively removes empty values from an object
  @param obj the object to purge
  @returns true if the object is an empty value
  */
function purge ( obj ) {
  switch ( true ) {
  case obj === null:
  case typeof obj === 'undefined':
  case typeof obj === 'string' && obj.trim() === '':
    return true

  case Array.isArray( obj ):
    for ( let i = obj.length - 1; i >= 0; i-- ) {
      if ( purge( obj[i] ) ) obj.splice( i, 1 )
    }
    return obj.length === 0

  case typeof obj === 'object':
    Object.keys( obj ).forEach( ( key ) => {
      if ( purge( obj[key] ) ) delete obj[key]
    } )
    return Object.keys( obj ).length === 0

  default:
    return false
  }
}