簡體   English   中英

檢查字符串數組與對象數組並在每種情況下返回一些內容

[英]Check array of strings against array of objects and return something per each case

我有一個簡單的數組問題:我有兩個不同的 arrays:一個帶有字符串,一個帶有對象。 我需要以某種方式相互檢查:對象數組需要檢查 object 的屬性是否包含在字符串數組中,並在每種情況下返回響應。

const colors = ["blue", "pink", "red", "green", "yellow", "orange", "white"]

const objColors = [{name:"pink", value: true}, {name:"green", value: true}, {name: "white", value: false}] 

我預期的響應數組將類似於:

const res = [false, true, false, true, false, false, false]

我不知道如何解決這個問題,因為我嘗試了幾件事都沒有成功。 我嘗試了兩次迭代,但它給了我錯誤的響應。 我也嘗試過包含的方法,但是我只能檢查我的 objColors 數組,因此我沒有得到我需要檢查的所有情況的響應

let res = objects.map(x => (strings.includes(x.name)))

有人可以給我一個關於如何檢查它們以獲得所需響應的提示嗎? 提前致謝

首先將對象數組轉換為更易於檢查的結構 - 可能是 Map 或一組正確的值。 然后您可以 map colors 數組並查找相關值。

 const colors = ["blue", "pink", "red", "green", "yellow", "orange", "white"]; const objColors = [{name:"pink", value: true}, {name:"green", value: true}, {name: "white", value: false}]; const trueColors = new Set( objColors.filter(({ value }) => value).map(({ name }) => name) ); const res = colors.map(color => trueColors.has(color)); console.log(res);

使用 object 的方法。

 const colors = ["blue", "pink", "red", "green", "yellow", "orange", "white"], objColors = [{ name: "pink", value: true }, { name: "green", value: true }, { name: "white", value: false }], wanted = Object.fromEntries(objColors.map(({ name, value }) => [name, value])), result = colors.map(c =>;.wanted[c]); console.log(result);

暫無
暫無

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

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