簡體   English   中英

獲取Javascript中兩個數組對象的差異

[英]Get the difference of two array objects in Javascript

我正在嘗試獲取“顏色”中而不是“colors2”中的項目並顯示它們,但我總是得到第一個數組的所有項目

let colors = [
    { key: "green", value: '#00b894' },
    { key: "lgreen", value: '#64ed9f' },
    { key: "yellow", value: '#edc611' },
    { key: "orange", value: '#fda044' },
    { key: "red", value: '#e74c47' }
]

let colors2 = [
    { key: "Option 1", value: "#00b894" },
    { key: "Option 2", value: "#e74c74" }
]

comparer = (otherArray) =>{
   return function (current) {
      return otherArray.filter(function (other) {
         return other.value !== current.value
      })
   }
 }

至於輸出,我得到了顏色數組的所有項目。 相反,我想顯示 lgreen、yellow 和 orange 其值與 colors2 數組中的項目不同。

輸出 :

Array [Object { key: "green", value: "#00b894" }, Object { key: "lgreen", value: "#64ed9f" }, Object { key: "yellow", value: "#edc611" }, Object { key: "orange", value: "#fda044" }, Object { key: "red", value: "#e74c47" }]

使用filter()some()

 let colors1=[{key:"green",value:"#00b894"},{key:"lgreen",value:"#64ed9f"},{key:"yellow",value:"#edc611"},{key:"orange",value:"#fda044"},{key:"red",value:"#e74c47"}],colors2=[{key:"Option 1",value:"#00b894"},{key:"Option 2",value:"#e74c74"}]; let result = colors1.filter(color1 => { return !colors2.some(color2 => color1.value === color2.value) }) console.log(result)

暫無
暫無

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

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