从json数组中删除未定义的键

时间:2019-06-06 19:14:12

标签: javascript javascript-objects

我有以下JS数组。删除所有带有未定义键的行的最佳方法是什么?

json=[{email: "1234569@hhh.pt", first: "Joao", last: "Bastos", gender: "Male", phone: "3.51939e+11"},
      {email: "", first: undefined, last: undefined, gender: undefined, phone: undefined}, 
      (...)];

我尝试了以下代码,但无法正常工作。我在做什么错了?

cleanEmptyRows(json){

var i=0;
var row_to_remove=[];

json.forEach(function(element) {
    for (var key in element) {
        if(element[key]==null){
        row_to_remove.push(i);
        break;
        }
    }
    i++;
});


row_to_remove.forEach(function(element){
    var index = json.indexOf(element);
    if (index > -1) {
        json.splice(index, 1);
    }
});

3 个答案:

答案 0 :(得分:3)

简单解决方案 JSON.parse(JSON.stringify(x))

var t = [{email: "1234569@hhh.pt", first: "Joao", last: "Bastos", gender: "Male", phone: "3.51939e+11"},
      {email: "", first: undefined, last: undefined, gender: undefined, phone: undefined}];

     
console.log(JSON.parse(JSON.stringify(t)));

如果要删除整行,则可以遵循以下代码,

var t = [{email: "1234569@hhh.pt", first: "Joao", last: "Bastos", gender: "Male", phone: "3.51939e+11"},
      {email: "", first: undefined, last: undefined, gender: undefined, phone: undefined},
      {email: "1234569@hhh.pt", first: "Joao", last: "Bastos", gender: "Male", phone: undefined}];

var resultArray = t.filter((row) => {
    var ignoreValue = Object.values(row).some(elem => elem === undefined);
    return !ignoreValue ? true : false;
});
console.log(resultArray);

答案 1 :(得分:0)

一种简单的方法是对JSON进行字符串化和解析。

let jsonTest = { foo: 'foo', bar: undefined };
let allDefined = JSON.parse(JSON.stringify(jsonTest));

您也可以通过删除未定义的属性来做到这一点。如果没有平面对象,则可以使其递归。

let jsonTest = { foo: 'foo', bar: undefined };
Object.keys(jsonTest).forEach((key) => {

    if (typeof jsonTest[key] == 'undefined') { 

        delete jsonTest[key];
    }
});

答案 2 :(得分:0)

尝试

<svg
    xmlns="http://www.w3.org/2000/svg"
    viewBox="0 0 400 300" width="400" height="300">
    <rect x="100" y="50" width="200" height="200"
        stroke="green" fill="gray" stroke-width="10" />
</svg>

json.map(x=> Object.keys(x).map(k=> x[k]===undefined ? delete x[k]:0));