過濾陣列中帶有空值的物件 JavaScript


假設我們有一個包含某公司員工資訊的陣列。但陣列包含一些錯誤資料,比如指向空字串或錯誤值。我們的任務是編寫一個函式,該函式接收陣列,清除名稱鍵為 null 或 undefined 或空字串的物件,並返回新的物件。

物件陣列如下所示 −

let data = [{
   "name": "Ramesh Dhiman",
   "age": 67,
   "experience": 45,
   "description": ""
}, {
      "name": "",
      "age": 31,
      "experience": 9,
      "description": ""
}, {
      "name": "Kunal Dhiman",
      "age": 27,
      "experience": 7,
      "description": ""
}, {
      "name": "Raman Kumar",
      "age": 34,
      "experience": 10,
      "description": ""
}, {
      "name": "",
      "age": 41,
      "experience": 19,
      "description": ""
   }
]

讓我們為該函式編寫程式碼 −

示例

let data = [{
   "name": "Ramesh Dhiman",
   "age": 67,
   "experience": 45,
   "description": ""
}, {
      "name": "",
      "age": 31,
      "experience": 9,
      "description": ""
}, {
      "name": "Kunal Dhiman",
      "age": 27,
      "experience": 7,
      "description": ""
}, {
      "name": "Raman Kumar",
      "age": 34,
      "experience": 10,
      "description": ""
}, {
      "name": "",
      "age": 41,
      "experience": 19,
      "description": ""
   }
]
const filterUnwanted = (arr) => {
   const required = arr.filter(el => {
      return el.name;
   });
   return required;
};
console.log(filterUnwanted(data));

輸出

控制檯中的輸出將為 −

[
   { name: 'Ramesh Dhiman', age: 67, experience: 45, description: '' },
   { name: 'Kunal Dhiman', age: 27, experience: 7, description: '' },
   { name: 'Raman Kumar', age: 34, experience: 10, description: '' }
]

更新於:24-Aug-2020

2K+ 瀏覽

啟動你的 職業生涯

完成課程認證。

開始
廣告