如果对象的所有属性为空,则从对象数组中删除对象

时间:2018-11-04 03:59:08

标签: javascript arrays object

我有一个对象数组,其中每个对象都有某些属性。我想从数组中删除为对象内所有属性分配了空字符串的对象。

示例:

var x = [{
   "userName" : "XYZ",
   "age": 22,
   "gender": "M"
}, {
   "userName" : "ABC",
   "age": 23,
   "gender": "M"
}, {
   "userName" : "Mohan",
   "age":"",
   "gender": ""
}, {
   "userName" : "",
   "age":"",
   "gender": ""
}]

结果应为

[{
   "userName" : "XYZ",
   "age": 22,
   "gender": "M"
}, {
   "userName" : "ABC",
   "age": 23,
   "gender": "M"
}, {
   "userName" : "Mohan",
   "age":"",
   "gender": ""
}]

1 个答案:

答案 0 :(得分:0)

您可以结合使用filtereveryObject.values

const x = [{
   "userName" : "XYZ",
   "age": 22,
   "gender": "M"
}, {
   "userName" : "ABC",
   "age": 23,
   "gender": "M"
}, {
   "userName" : "Mohan",
   "age":"",
   "gender": ""
}, {
   "userName" : "",
   "age":"",
   "gender": ""
}]

const y = x.filter(z => !Object.values(z).every(w => w ===""))

console.log(y)