遍历json为空数组值

时间:2014-12-29 11:03:35

标签: javascript json object

我有一个json以下

{
"loanDetails": [
{
  "vehicleDetail": {
    "RCBookImageReferences": {
      "imagePathReferences": [
        {

        }
      ]
    }
  },
  "chargeDetails": [
    {

    }
  ],
  "commissionDetails": [
    {

    }
  ],
  "disbursementDetails": [
    {

    }
  ]
}

] }  在上面的json我需要遍历每个键,如果我发现它是emty然后将父设置为空数组,即输出应如下所示

{"loanDetails":[]}

我使用下面的代码

function isEmpty(obj) {
for(var prop in obj) {
    if(obj.hasOwnProperty(prop))
        return false;
}

return true;
}

但它并没有给我预期的结果。我被困在这里任何帮助都会有所帮助。

5 个答案:

答案 0 :(得分:1)

函数clean接受一个对象并循环其键,递归调用clean 在每个对象值属性上。 如果清理结果是空对象,请删除有问题的密钥。 如果对象本身变为空,则返回undefined,触发删除在更高级别保存该对象的属性。

function clean(obj) {
    var isEmpty = true;
    for (var key in obj) {
        var val = obj[key];
        if (val === null || typeof val !== 'object' || (obj[key] = clean(val))) {
            isEmpty = false;
        } else {
            delete obj[key];
        }
    }
    return isEmpty ? undefined : obj;
}

>> a = { x: 1, b: { y: [] }, c: { d: { } } }
>> clean(a)
<< Object {x: 1}

答案 1 :(得分:0)

您的JSON字符串无效。更正后,您可以使用reviver函数参数(请参阅MDN)删除“空”数组(也就是您指定条件的属性)。

要清楚,reviver函数负责遍历解析对象的所有级别。如果它返回undefined,则从对象中删除该属性。因此,代码段中使用的reviver将删除包含空对象或空数组的数组的所有属性。

该片段演示了这一点。

// json string corrected
var foo = '{"loanDetails": [{"vehicleDetail": {"RCBookImageReferences": '+
          '{"imagePathReferences": [{}]}}, "chargeDetails": [{}],'+
          '"commissionDetails": [{}],"disbursementDetails": [{}]}]}';

// parse it, using reviver parameter
var fooparsed = JSON.parse( foo,
                            function (key, value) { //<= reviver here
                                return (value.length && value.length == 1 && 
                                        value[0] instanceof Object && 
                                        Object.keys(value[0]).length == 0) ||
                                        value instanceof Array && !value.length
                                     ? undefined : value; 
                            }
                );
// print
Helpers.log2Screen( Object.print(fooparsed) );
<script src="http://kooiinc.github.io/JSHelpers/Helpers-min.js"></script>

答案 2 :(得分:0)

这应该使它递归。有两个解决方案。

解决方案1:空测试功能

var boolValue = true;
for(var prop in obj) {
    if(obj.hasOwnProperty(prop) && typeof obj[prop] === 'object')
    {
        boolValue = recursiveIsEmpty(obj[prop]);
    }
    else
    {
        return false;
    }
}

    return boolValue ;


//test and set empty string
recursiveIsEmpty(jsonDataObj['loanDetails']) ? jsonDataObj['loanDetails'] = [] : null;

解决方案2递归空函数,清空父obj

function recursiveIsEmpty(obj) {
    var boolValue = true;
        for(var prop in obj) {
            if(obj.hasOwnProperty(prop) && typeof obj[prop] === 'object')
            {
                boolValue = recursiveIsEmpty(obj[prop]);
                if (boolValue)
                {
                    delete obj[prop]; //an object is empty. Delete from parent;
                }
            }
            else
            {
                return false;
            }
        }

    return boolValue; //returns an empty object
}

recursiveIsEmpty(jsonDataObj['loanDetails']) //returns jsonDataObj['loanDetails'] = [];

检查obj是否具有作为对象的属性。如果是这样,加载该对象并检查它的属性。如果不是return false,因为它将是字符串或数字,并确认该对象不为空。

答案 3 :(得分:-1)

如果您使用ajax执行此操作,那么您应该使用javascript对jason数组进行串行化。

在通过json传递数据时

data: "your data",

使用此

data:$(form).serialize(),

它将传递您传递的该表单的所有键,

如果你想看到它的结果,试着在控制台上打印它

答案 4 :(得分:-1)

&#13;
&#13;
var inputObj = {
  "loanDetails": [{
    "vehicleDetail": {
      "RCBookImageReferences": {
        "imagePathReferences": [{}]
      }
    },
    "chargeDetails": [{}],
    "commissionDetails": [{}],
    "disbursementDetails": [{}]
  }, {
    "vehicleDetail": {
      "RCBookImageReferences": {
        "imagePathReferences": [{
          "Valid": "Working"
        }]
      }
    },
    "chargeDetails": [{}],
    "commissionDetails": [{}],
    "disbursementDetails": [{}]
  }],
  "Superman": {
    "Name": ""
  },
  "SpiderMan": {
    "Name": "Senthil"
  }
}

function flatten(target, opts) {
  var output = {},
    opts = opts || {},
    delimiter = opts.delimiter || '.'

  function getkey(key, prev) {
    return prev ? prev + delimiter + key : key
  };

  function step(object, prev) {
    Object.keys(object).forEach(function(key) {
      var isarray = opts.safe && Array.isArray(object[key]),
        type = Object.prototype.toString.call(object[key]),
        isobject = (type === "[object Object]" || type === "[object Array]")

      if (!isarray && isobject) {
        return step(object[key], getkey(key, prev))
      }

      output[getkey(key, prev)] = object[key]
    });
    if (Object.keys(object) == "") {
      if (object instanceof Array) {
        output[prev] = [];
      } else {
        output[prev] = {};
      }
    }
  };
  step(target)
  return output
};

function unflatten(target, opts) {
  var opts = opts || {},
    delimiter = opts.delimiter || '.',
    result = {}

  if (Object.prototype.toString.call(target) !== '[object Object]') {
    return target
  }

  function getkey(key) {
    var parsedKey = parseInt(key)
    return (isNaN(parsedKey) ? key : parsedKey)
  };

  Object.keys(target).forEach(function(key) {
    var split = key.split(delimiter),
      firstNibble, secondNibble, recipient = result

    firstNibble = getkey(split.shift())
    secondNibble = getkey(split[0])

    while (secondNibble !== undefined) {
      if (recipient[firstNibble] === undefined) {
        recipient[firstNibble] = ((typeof secondNibble === 'number') ? [] : {})
      }

      recipient = recipient[firstNibble]
      if (split.length > 0) {
        firstNibble = getkey(split.shift())
        secondNibble = getkey(split[0])
      }
    }

    // unflatten again for 'messy objects'
    recipient[firstNibble] = unflatten(target[key])
  });

  //Array Check
  var keys = Object.keys(result);
  if (keys.length > 0 && keys[0] === "0") {
    var output = [];
    keys.forEach(function(key) {
      output.push(result[key])
    });
    return output;
  }
  return result
};

var flatted = flatten(inputObj);
var keys = Object.keys(flatted);
keys.forEach(function(key) {
  if (JSON.stringify(flatted[key]) === "{}" || JSON.stringify(flatted[key]) == "") {
    // console.log(key)
    delete flatted[key];
    var paths = key.split(".");
    if (paths.length >= 2) {
      var int = parseInt(paths[1])
      if (isNaN(int)) {
        key = paths[0];
        flatted[key] = {};
      } else {
        key = paths[0] + "." + int;
        flatted[key] = {};
      }
      var newKeys = Object.keys(flatted);
      for (var j = 0; j < newKeys.length; j++) {
        var omg = newKeys[j];
        if (omg.indexOf(key) != -1 && omg.length > key.length) {
          delete flatted[key];
        }
      }
    }
  }
})
console.log(flatted)
var output = unflatten(flatted);
alert(JSON.stringify(output))
&#13;
&#13;
&#13;