Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add conditions to an object dynamically from an Array

Tags:

javascript

I have an object like this, that needs to be sent to an API -

var data = { 
    field : "category"
    value : "order"
}

Now, this API also needs some conditions needed to be sent as nested objects. Something like this -

var data ={ 
    field : "category"
    value : "order"
    AND : {
      field : "circuit"
      value : "ninth"
      OR : {
         field : "second"
         value : "abc",
         //more conditions here possible //
      }
}

So, basically, a condition is nested inside a condition. EDIT:: Note - Each condition added into the conditions array has to be nested into the previous condition

Now, I have an array of conditions -

conditionsArray = [
{filter: "AND", field: "circuit", value: "ninth"},
{filter: "OR", field: "second", value: "abc"}
]

How do I add conditions to data object from this conditionsArray in the most optimal way?

var data = { 
    field : "category"
    value : "order"
}

Thank you for your time.

EDIT: sorry, I forgot to add what I have tried so far -

I have been trying to just form an object but this is by no means a good solution.

const check = () => {
    console.log(conditionsArray);
    const data: any = { ...fieldValue };
    conditionsArray.forEach((condition: any) => {
      const { filter, name, value } = condition;
      const { AND, OR, NOT } = data;
      if (AND || OR || NOT) {
        if (AND) {
          data["AND"][filter] = { name, value };
        }
        if (OR) {
          data["OR"][filter] = { name, value };
        }
        if (NOT) {
          data["NOT"][filter] = { name, value };
        }
      } else {
        data[filter] = { name, value };
      }
    });
    console.log(data,"log data");
  };
like image 485
Atin Singh Avatar asked Sep 06 '25 03:09

Atin Singh


2 Answers

You could reduce the array and return the nested object for the next iteration.

const 
    data = { field: "category", value: "order" },
    conditionsArray = [{ filter: "AND", field: "circuit", value: "ninth" }, { filter: "OR", field: "second", value: "abc" }];

conditionsArray.reduce((o, { filter, ...rest }) => o[filter] = rest, data);

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 64
Nina Scholz Avatar answered Sep 07 '25 20:09

Nina Scholz


Using recursion :

function addConditions(data, conditions) {
    if (conditions.length == 0) { return data; }
    var topMostCondition = conditions[0];
    var objectToAdd = { field : topMostCondition.field, value : topMostCondition.value };
    data[topMostCondition.filter] = addConditions(objectToAdd, conditions.splice(1));
    return data;
}
like image 30
Aaron Avatar answered Sep 07 '25 21:09

Aaron