2016-08-13 137 views
-1

我擁有對象數組。像這樣使用Lodash或基於屬性名稱的Javascript過濾對象數組

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"}] 

任何人可以幫助我在此

回答

4

這是簡單的array .filter() method

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值放在引號中,因爲它們似乎是字符串值。

2
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)); 
+2

不錯的一個。你甚至可以寫'result.filter(hasProperties);'。 – Tholle

+0

@Tholle謝謝。我不知道。 – James