通过AngularJS删除嵌套json对象中的空字符串

时间:2017-01-13 09:57:28

标签: javascript angularjs json

我有一个嵌套的json对象,我需要删除空值并创建新的json,它应该只包含数据对象。 json文件:

myData = [{
    "id": 1,
    "values": [{
        "value": ""
    }]
}, {
    "id": 2,
    "values": [{
        "value": 213
    }]

}, {
    "id": 3,
    "values": [{
        "value": ""
    }, {
        "value": ""
    }, {
        "value": "abc"
    }]

},{
    "id": 4,
    "values": [{
        "value": ""
    }]
},{
    "id": 33,
    "values": [{
        "value": "d"
    }]
}];

输出应为:

myNewData = [{
    "id": 2,
    "values": [{
        "value": 213
    }]

}, {
    "id": 3,
    "values": [{
        "value": "abc"
    }]

},{
    "id": 33,
    "values": [{
        "value": "d"
    }]
}];

到目前为止,我创造了这个:

    angular.module('myapp',[])
    .controller('test',function($scope){
    $scope.myData = [{
        "id": 1,
        "values": [{
            "value": ""
        }]
    }, {
        "id": 2,
        "values": [{
            "value": 213
        }]

    }, {
        "id": 3,
        "values": [{
            "value": ""
        }, {
            "value": ""
        }, {
            "value": "abc"
        }]

    },{
        "id": 4,
        "values": [{
            "value": ""
        }]
    },{
        "id": 33,
        "values": [{
            "value": "d"
        }]
    }];

})
.filter('filterData',function(){
    return function(data) {
        var dataToBePushed = [];
        data.forEach(function(resultData){
            if(resultData.values && resultData.values != "")
                dataToBePushed.push(resultData);
        });
        return dataToBePushed;
    }
});

HTML:

<div ng-app="myapp">
    <div ng-controller="test">
        <div ng-repeat="data in myData | filterData">
            Id:{{ data.id }}
            </br>
            Values: {{ data.values }}
        </div>
    </div>
</div>

我无法访问和删除值对象内的值。现在我只是使用ng-repeat显示数据,但我需要为此创建一个新的json文件。

6 个答案:

答案 0 :(得分:2)

您使用AngularJS控制器中的数组执行Array.prototype.map()Array.prototype.filter()。映射执行过滤器的所有对象以排除具有空值item.values.value的项,而不是过滤器以获取具有值的值的数组元素:

&#13;
&#13;
var myData = [{"id": 1,"values": [{	"value": ""}]}, {"id": 2,"values": [{"value": 213}]}, {"id": 3,"values": [{"value": ""}, {"value": ""}, {"value": "abc"}]}, {"id": 4,"values": [{"value": ""}]}, {"id": 33,"values": [{"value": "d"}]}],
    myDataFiltered = myData
      .map(function (item) {
        item.values = item.values.filter(function (itemValue) {
          return itemValue.value;
        });
        return item;
      })
      .filter(function (item) {
        return item.values.length;
      });

console.log(myDataFiltered);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

ES6:

myDataFiltered = myData
    .map(item => {
        item.values = item.values.filter(itemValue => itemValue.value);
        return item;
    })
    .filter(item => item.values.length);

答案 1 :(得分:0)

您可以使用多个for循环。

myData = [{
    "id": 1,
    "values": [{
        "value": ""
    }]
}, {
    "id": 2,
    "values": [{
        "value": 213
    }]

}, {
    "id": 3,
    "values": [{
        "value": ""
    }, {
        "value": ""
    }, {
        "value": "abc"
    }]

},{
    "id": 4,
    "values": [{
        "value": ""
    }]
},{
    "id": 33,
    "values": [{
        "value": "d"
    }]
}];

function clone(obj){ return JSON.parse(JSON.stringify(obj));}
var result = [];
for(var i = 0; i < myData.length; i++){
	var current = clone(myData[i]);
  for(var j = 0; j < current.values.length; j++){
    if(current.values[j].value == null || current.values[j].value == ""){
      current.values.splice(j, 1);
      j--;
    }
  }
  if(current.values.length > 0) result.push(current);
}
console.log(myData);
console.log(result);

答案 2 :(得分:0)

如果要完全删除它们,可以像这样迭代数组;

angular.forEach($scope.myData, function(data){
    for(var i=0; i < data.values.length; i++){
         if(data.values[i] !== ""){
              break;
         }
         delete data;
    }
});

if语句检查数组中的所有值,如果它不等于&#34;&#34;则中断,否则如果所有值都是=&#34;&#34;它删除了对象。

希望它有所帮助!

答案 3 :(得分:0)

试试这个:

&#13;
&#13;
var myData = [{"id": 1,"values": [{ "value": ""}]}, {"id": 2,"values": [{"value": 213}]}, {"id": 3,"values": [{"value": ""}, {"value": ""}, {"value": "abc"}]}, {"id": 4,"values": [{"value": ""}]}, {"id": 33,"values": [{"value": "d"}]}]

let result=[],p=[];
myData.filter(el => {    
     p=[]; 
     el.values.filter(k => {k.value != '' ? p.push({value : k.value}) : null}); 
     if(p.length) result.push({id : el.id, values : p})
})
    
console.log('result', result);
&#13;
&#13;
&#13;

答案 4 :(得分:0)

这是一个完成这项工作的递归函数。

仅当myData是数组并且其中的值或其子项是对象的集合时,这才有效。

var myData = [{"id": 1, "values": [{"value": ""}] }, {"id": 2, "values": [{"value": 213 }] }, {"id": 3, "values": [{"value": ""}, {"value": ""}, {"value": "abc"}] },{"id": 4, "values": [{"value": ""}] },{"id": 6, "values": ""},{"id": 33, "values": [{"value": "d"}] }];

function removeEmptyValues (arr) {
    var res = false;

    /* Iterate the array */
    for (var i = 0; i < arr.length; i++) {
        /* Get the object reference in the array */
        var obj = arr[i];

        /* Iterate the object based on its key */
        for (var key in obj) {

            /* Ensure the object has the key or in the prototype chain */
            if (obj.hasOwnProperty(key)) {

                /* So, the object has the key. And we want to check if the object property has a value or not */
                if (!obj[key]) {

                    /*
                        If it has no value (null, undefined, or empty string) in the property, then remove the whole object,
                        And reduce `i` by 1, to do the re-checking
                    */
                    arr.splice(i--, 1);

                    /* Amd set whether the removal occurance by setting it to res (result), which we will use for the next recursive function */
                    res = true;

                    /* And get out from the loop */
                    break;
                }

                /* So, the object has a value. Let's check whether it's an array or not */
                if (Array.isArray(obj[key])) {

                    /* Kay.. it's an array. Let's see if it has anything in it */
                    if (!obj[key].length) {

                        /* There's nothing in it !! Remove the whole object again */
                        arr.splice(i--, 1);

                        /* Amd set whether the removal occurance by setting it to res (result), which we will use for the next recursive function */
                        res = true;

                        /* Yes.. gets out of the loop */
                        break;
                    }

                    /*
                        Now this is where `res` is being used.
                        If there's something removed, we want to re-do the checking of the whole object
                    */
                    if ( removeEmptyValues(obj[key]) ) {

                        /* Something has been removed, re-do the checking */
                        i--;
                    }
                }
            }
        }
    }

    return res;
}

removeEmptyValues (myData);

答案 5 :(得分:0)

你会采取正确的方式,但需要更多这样的操作:

&#13;
&#13;
try-catch
&#13;
context.evaluatePolicy(policy, localizedReason: ...) { (success: Bool, error: Error?) in
    DispatchQueue.main.async {
        if success {
            ...
        } else if let error = error as? LAError {
            switch error.code {
            case LAError.authenticationFailed:
            ...
            }
        }
    }
}
&#13;
&#13;
&#13;