使用'AND”、'OR”運算符搜尋 Json 對象
P粉029327711
P粉029327711 2023-09-06 10:23:16
0
1
552

我遇到一個問題,需要使用條件運算子字串搜尋 JSON 物件。

JSON 物件看起來像

let Data = [
  {Application: 'APIM', Owner: 'Vande Mataram','Customer Code': 'DJLFKASJF',Environment: 'Dev',OS: 'Linux',Region: 'EU','TEAM ': 'DemoTestCOE'},
  {TEAM: 'BCC'},
  {Team: 'DemoTestCOE','Customer Code': 'DJLFKASJF',Owner: 'Vande Mataram',Environment: 'Prod',Region: 'EU',Application: 'Ui-Path',OS: 'Windows'},
  {Application: 'MGMT','Customer Code': 'DJLFKASJF', os: 'Windows','Owner ': 'Vande Mataram', Region: 'East US 2',Team: 'DemoTestCOE',Environment: 'MGMT'  },
  {Application: 'PIER',Owner: 'Govindarajulu Balaji',OS: 'Windows',Region: 'DemoTestCOE', Environment: 'QA'}  
]

以及如下所示的條件字串..

let condition =
  '"Owner": "Vande Mataram" AND ("Application": "APIM" AND "Customer Code": "DJLFKASJF") OR ("Owner": "Vande Mataram" AND "Customer Code": "DJLFKASJF") OR "Owner": "Vande Mataram"'

沒有網路的運氣...如何實現這個,我無法將其帶到 SQL Server,因為它需要在 javascript 中完成。

我在網路上搜尋了將條件字串拆分為按運算子(AND/OR)拆分的數組,並在json資料物件中進行一一搜索,但是每個請求的條件字串都不同。並且努力正確實施運算符(AND/OR)。我不確定這是最好的主意

我需要幫助如何解決這個問題以滿足使用多個嵌套括號提供的任何類型的條件。

謝謝

P粉029327711
P粉029327711

全部回覆(1)
P粉174151913

Data 只是一個物件數組,因此您可以使用 Array.filter

let Data = [
  {Application: 'APIM', Owner: 'Vande Mataram','Customer Code': 'DJLFKASJF',Environment: 'Dev',OS: 'Linux',Region: 'EU','TEAM ': 'DemoTestCOE'},
  {TEAM: 'BCC'},
  {Team: 'DemoTestCOE','Customer Code': 'DJLFKASJF',Owner: 'Vande Mataram',Environment: 'Prod',Region: 'EU',Application: 'Ui-Path',OS: 'Windows'},
  {Application: 'MGMT','Customer Code': 'DJLFKASJF', os: 'Windows','Owner ': 'Vande Mataram', Region: 'East US 2',Team: 'DemoTestCOE',Environment: 'MGMT'  },
  {Application: 'PIER',Owner: 'Govindarajulu Balaji',OS: 'Windows',Region: 'DemoTestCOE', Environment: 'QA'}  
]
// and the condition string like below..
/*
let condition =
  '"Owner": "Vande Mataram" AND ("Application": "APIM" AND "Customer Code": "DJLFKASJF") OR ("Owner": "Vande Mataram" AND "Customer Code": "DJLFKASJF") OR "Owner": "Vande Mataram"'
*/
console.log(Data.filter(item => {
    return item.Owner === 'Vande Mataram' 
    && (item.Application === "APIM" && item['Customer Code'] === "DJLFKASJF") 
    || (item.Owner === 'Vande Mataram' && item['Customer Code'] === "DJLFKASJF")
    || item.Owner === 'Vande Mataram';
}));
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!