Jackson Christopher
Jackson Christopher

Reputation: 101

Extract data from Nested Array Object

The following is JSON is generated from the Search Builder Plugin of Datatables and I would like to display the output in the following format using javascript without use of any library.

(Registration=1)OR((Registration=2)OR(Number=3))OR(Number=4)OR(Station=Yes)
var sbfilter = {
  "criteria": [
    {
      "condition": "=",
      "data": "Registration",
      "value": [
        "1"
      ]
    },
    {
      "criteria": [
        {
          "condition": "=",
          "data": "Registration",
          "value": [
            "2"
          ]
        },
        {
          "condition": "=",
          "data": "Number",
          "value": [
            "3"
          ]
        }
      ],
      "logic": "OR"
    },
    {
      "condition": "=",
      "data": "Number",
      "value": [
        "4"
      ]
    },
    {
      "condition": "=",
      "data": "Station",
      "value": [
        "Yes"
      ]
    }
  ],
  "logic": "OR"
};

Upvotes: 0

Views: 231

Answers (1)

Rifat Bin Reza
Rifat Bin Reza

Reputation: 2781

This is what I can think of right now, using a loop and a recursion to go through every nested array and make the query string. The algorithm can be improved.

var sbfilter = {
  "criteria": [
    {
      "condition": "=",
      "data": "Registration",
      "value": [
        "1"
      ]
    },
    {
      "criteria": [
        {
          "condition": "=",
          "data": "Registration",
          "value": [
            "2"
          ]
        },
        {
          "condition": "=",
          "data": "Number",
          "value": [
            "3"
          ]
        }
      ],
      "logic": "OR"
    },
    {
      "condition": "=",
      "data": "Number",
      "value": [
        "4"
      ]
    },
    {
      "condition": "=",
      "data": "Station",
      "value": [
        "Yes"
      ]
    }
  ],
  "logic": "OR"
};
var query = '';
function makeQuery(criteria, logic) {
  criteria.forEach((c, idx, array)=>{
    if (c.criteria) {
      // Add a parentheses since it's the start of a sub query
      query+='('
      makeQuery(c.criteria, c.logic)
      // Close the parentheses
      query+=')'
    } else {
      query+= '('+c.data+c.condition+c.value[0]+')'
    }
    // Check if not the last condition then add the logic to it
    if (idx != array.length - 1) {
      query+=logic
    }
  })
}
makeQuery(sbfilter.criteria, sbfilter.logic)
console.log(query)

Upvotes: 1

Related Questions