簡體   English   中英

根據屬性名稱使用Lodash或Javascript過濾對象數組

[英]Filtering array of Objects Using Lodash or Javascript based on property name

我有對象數組。 像這樣

var result=[{"batchId":123, "licenseId":2345ef34, "name":"xxx"},
{"batchId":345, "licenseId":2345sdf334, "name":"www"},
{"batchId":145, "licenseId":234sdf5666, "name":"eee"},
{"batchId":455, "licenseId":asfd236645 },
{"batchId":678, "name":"aaa"}]

我想擁有包含所有三個屬性的數組。 輸出應該是這樣的。

[{"batchId":123, "licenseId":2345ef34, "name":"xxx"},
    {"batchId":345, "licenseId":2345sdf334, "name":"www"},
    {"batchId":145, "licenseId":234sdf5666, "name":"eee"}]

有人可以幫我嗎

使用array .filter()方法很簡單:

 var result=[ {"batchId":123, "licenseId":"2345ef34", "name":"xxx"}, {"batchId":345, "licenseId":"2345sdf334", "name":"www"}, {"batchId":145, "licenseId":"234sdf5666", "name":"eee"}, {"batchId":455, "licenseId":"asfd236645" }, {"batchId":678, "name":"aaa"} ]; var filtered = result.filter(function(v) { return "batchId" in v && "licenseId" in v && "name" in v; }); console.log(filtered); 

傳遞給.filter()的函數將針對數組中的每個元素調用。 您為其返回真實值的每個元素都將包含在結果數組中。

在上面的代碼中,我只是簡單地測試所有這三個特定屬性是否都存在,盡管您可以使用其他測試來獲得相同的數據結果:

 var result=[ {"batchId":123, "licenseId":"2345ef34", "name":"xxx"}, {"batchId":345, "licenseId":"2345sdf334", "name":"www"}, {"batchId":145, "licenseId":"234sdf5666", "name":"eee"}, {"batchId":455, "licenseId":"asfd236645" }, {"batchId":678, "name":"aaa"} ]; var filtered = result.filter(function(v) { return Object.keys(v).length === 3; }); console.log(filtered); 

請注意,您需要將licenseId值放在引號中,因為它們似乎是字符串值。

var result = [{
  "batchId": 123,
  "licenseId": '2345ef34',
  "name": "xxx"
}, {
  "batchId": 345,
  "licenseId": '2345sdf334',
  "name": "www"
}, {
  "batchId": 145,
  "licenseId": '234sdf5666',
  "name": "eee"
}, {
  "batchId": 455,
  "licenseId": 'asfd236645'
}, {
  "batchId": 678,
  "name": "aaa"
}];

function hasProperties(object) {
  return object.hasOwnProperty('batchId') && object.hasOwnProperty('licenseId') && object.hasOwnProperty('name')
}

result.filter(e => hasProperties(e));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM