Home  >  Q&A  >  body text

Search Json objects using "AND", "OR" operators

I have a problem where I need to search a JSON object using a conditional operator string.

The JSON object looks like

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 shown 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"'

No luck with the internet... How to implement this, I can't bring it to SQL Server as it needs to be done in javascript.

I searched online to split the condition string into an array split by operators (AND/OR) and searched one by one in the json data object, but the condition string for each request was different. And work on implementing operators (AND/OR) correctly. I'm not sure this is the best idea

I need help how to solve this problem to satisfy any kind of condition provided using multiple nested brackets.

Thanks

P粉029327711P粉029327711409 days ago598

reply all(1)I'll reply

  • P粉174151913

    P粉1741519132023-09-07 00:08:39

    Data is just an array of objects, so you can use 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';
    }));

    reply
    0
  • Cancelreply