簡體   English   中英

驗證數組內屬性對象的值

[英]Verify value of property object inside Array

我有以下數組:

arrayObject = [
    { type: "one" },
    { type: "two" },
    { type: "other" },
];

而且我還有以下帶有值的數組:

types = [
    "one",
    "other"
];

我需要驗證這兩個值是否存在,如果不存在,則必須阻止它們在流程中前進,目前我正在做的是:

arrayObject.filter(object => types.includes(object.type))

並且此代碼在不存在時返回我,但在一個或另一個不存在時也返回我,但是我需要知道這兩個是否存在,這對我不起作用

使用every

if (types.every(t => arrayObject.findIndex(a => a.type === t) > -1))

您還可以將Array.fromArray.everyArray.includes

 const arrayObject = [{ type: "one" }, { type: "two" }, { type: "other" }]; const types = ["one", "other"]; const result = types.every(t => Array.from(arrayObject, x=> x.type).includes(t)) console.log(result) 

您也可以使用Array.some獲得更簡潔的解決方案:

 const arrayObject = [{ type: "one" }, { type: "two" }, { type: "other" }]; const types = ["one", "other"]; const result = types.every(t => arrayObject.some(x => x.type === t)) console.log(result) 

並且由於您有lodash標簽:

 const arrayObject = [{ type: "one" }, { type: "two" }, { type: "other" }]; const types = ["one", "other"]; const result = _.every(types, x => _.some(arrayObject, {type: x})) console.log(result) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script> 

使用_.map()arrayObject_.map() type 使用_.intersection() ,並將結果長度與types數組的長度進行比較:

 const arrayObject = [{"type":"one"},{"type":"two"},{"type":"other"}]; const types = ["one","other"]; const result = _.eq( _.intersection(types, _.map(arrayObject, 'type')).length , types.length); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script> 

暫無
暫無

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

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