Skip to content Skip to sidebar Skip to footer

Manipulating A Complex Object Based On An Input Array

I have an complex object and based on an input array I need to modify properties inside of this complex object. Illustration is shown below. I need to group them based on field val

Solution 1:

You could collect all same fields by a grouping and assign the values from grouping to and property.

var filterObj = { feature: "test", filter: { and: [{ field: "field1", value: "1" }] } },
    obj = [{ field: "field1", value: "2" }, { field: "field2", value: "3" }, { field: "field2", value: "4" }, { field: "field3", value: "5" }],
    groups = obj.reduce(
        (r, o) => {
            if (r[o.field]) {
                if (!('or'in r[o.field])) r[o.field] = { or: [r[o.field]] };
                r[o.field].or.push(o);
            } else {
                r[o.field] = o;
            }
            return r;
        },
        (filterObj.filter.and || []).reduce((r, o) => {
            r['or'in o ? o.or[0].field : o.field] = o;
            return r;
        }, {}));

filterObj.filter.and = Object.values(groups);

console.log(filterObj);
.as-console-wrapper { max-height: 100%!important; top: 0; }

Solution 2:

//This is the source object where I need to add the below "arr" based on groupinglet filterObj = {
  "feature": "test",
  "filter": {
    "and": [
      { "field": "field1", "value": "1" }
    ]
  }
};

//This array needs to be added to above object by grouping based on fieldlet obj = [
  { "field": "field1", "value": "2" },
  { "field": "field2", "value": "3" },
  { "field": "field2", "value": "4" },
  { "field": "field3", "value": "5" }
]
//obj = [{ "field": "field1", "value": "2" }]let all_filters = [];
if (filterObj.filter.and && filterObj.filter.and.hasOwnProperty('or')) {
  all_filters = [...filterObj.filter.and.or];
} elseif (filterObj.filter.and) {
  all_filters = [...filterObj.filter.and];
}
const all_objs = [...obj, ...all_filters];
// const all_objs = [...obj, ...filterObj.filter.and];const uniqKeys = all_objs.reduce((acc, curr) => [...newSet([...acc, curr.field])], []);
const updateItems = uniqKeys.map(obj => {
  const filter_items = all_objs.filter(item => item.field === obj);
  let resultObj = {};
  if (filter_items && filter_items.length > 1) {
    resultObj.or = [...filter_items];
  } elseif (filter_items && filter_items.length == 1) {
    resultObj = { ...filter_items[0] };
  }
  return resultObj;
})

var result = {...filterObj, filter: { and: [...updateItems] }};

console.log(result);

Please not that your input has "fiedl2" and "field2" (two different). I updated to same field name in the data here

Post a Comment for "Manipulating A Complex Object Based On An Input Array"