簡體   English   中英

檢查對象數組中的任何鍵是否包含來自數組數組對象的值的最佳方法是什么?

[英]What would be the best way to check if any of the keys in an array of objects contain a value from an object of arrays array?

我想通過檢查arrOfObjs.name存在任何項目技術來創建過濾系統。 如果是,那么它將通過過濾器並被包含/顯示到 DOM。 更具體地說,是 VueJS 中的計算值。

例子:

arrOfObjs = [{name: 'test1', image: 'testing1'}, {name: 'test2', image:'testing2'}]
projects: 
[
      {
        name: "testproject",
        description: "lorem ipsum",
        technologies: ["test2", "test7", "test3"]
      },
      {
        name: "atest",
        description: "lorem ipsum",
        technologies: ["test1", "test2", "test5"]
      },
]

我的嘗試:

computed: {
  myComputedVal () {
    projs = []
    this.projects.forEach(p => {
      p.technologies.forEach(t => {
        this.arrOfObjs.filter(o => {
          if (o.name == t) {
            return p // maybe projs = [...projs, p] and return projs
          }
        })
      })
    })
  }
}

我想檢查arrOfObjs.name中是否存在技術中的任何值,如果存在,則返回項目或將其推送到一個數組,以便稍后將此對象數組作為計算值返回。 目前,什么都沒有發生。

我認為使用下面的代碼片段,您可以過濾掉那些在arrOfObjs數組的name屬性中存在任何technologies項目。

使用flatMap()您可以首先將所有名稱作為字符串放入數組中。 然后按照您最初的需要使用filter()並使用some()includes()組合,如果任何技術元素在names數組中表示,則只需過濾掉項目,例如:

({technologies}) => technologies.some(t => names.includes(t))

如果您想檢查所有元素是否都存在,那么建議使用every()例如:

({technologies}) => technologies.every(t => names.includes(t))

可能的解決方案 - 用some()表示示例:

 const arrOfObjs = [{name: 'test1', image: 'testing1'}, {name: 'test2', image:'testing2'}], projects = [{name: "testproject",description: "lorem ipsum",technologies: ["test2", "test7", "test3"]}, {name: "atest",description: "Lorem ipsum", technologies: ["test1", "test2", "test5"] }]; const names = arrOfObjs.flatMap(e => e.name); const result = projects.filter( ({technologies}) => technologies.some(t => names.includes(t) // technologies.every(t => names.includes(t) // if all needed ) ); console.log(result);

我希望這有幫助!

暫無
暫無

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

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