WillKre
WillKre

Reputation: 6158

Loop through infinitely nested object & Construct string

I'm using this query component in one of my projects so that users can construct a query.

I'm having difficulty parsing it into an actual example query, for example for this object outputted by the component:

const queryParams = {
  "rules": [
    {
      "rules": [
        {
          "field": "firstName",
          "value": "John",
          "operator": "="
        },
        {
          "field": "lastName",
          "value": "Doe",
          "operator": "="
        }
      ],
      "combinator": "and"
    },
    {
      "rules": [
        {
          "field": "age",
          "value": "20",
          "operator": "="
        },
        {
          "field": "address",
          "value": "London",
          "operator": "="
        }
      ],
      "combinator": "and"
    }
  ],
  "combinator": "and"
}

I need to create a function that would output a more user-friendly readable output as such:

((FirstName = John AND LastName = Doe) AND (AGE = 20 AND Address = London))

I've given it a go but the difficulty I'm finding is that:

The way I'm currently trying will not work dynamically, so any help or guidance would be greatly appreciated.

Thanks

Upvotes: 2

Views: 61

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386634

You could take a recursive approach and build either a rules set or a final comparison.

It works by checking the rules property:

  • If given, then the rules are mapped with a recursive call of the function.

    The result of this call is joined with an upper case combinator property and wrapped into a wanted spaced string with parenthesis.

  • If not, then take a new string with field, operator and value property.

function combine(object) {
    return 'rules' in object
        ? `(${object.rules.map(combine).join(` ${object.combinator.toUpperCase()} `)})`
        : `${object.field} ${object.operator} ${object.value}`;
}

var data = { rules: [{ rules: [{ field: "firstName", value: "John", operator: "=" }, { field: "lastName", value: "Doe", operator: "=" }], combinator: "and" }, { rules: [{ field: "age", value: "20", operator: "=" }, { field: "address", value: "London", operator: "=" }], combinator: "and" }], combinator: "and" },
    result = combine(data);

console.log(result);

Upvotes: 3

Related Questions