Combining and aggregating an array of objects into a intricate object: JavaScript

I have a sophisticated object that contains an array of objects which must be added (grouped by field and then added).

Below are the formats for both:

// This is the original object where I want to add the "arr" below based on grouping

let filterObj = {
      "feature": "test",
      "filter": {
                 "and": [
                          { "field": "field1","value": "1"}
                        ]
                }
};

// This array should be added to the above object after grouping by field
let obj = [
           {"field": "field1","value": "2"},
           {"field": "fiedl2","value": "3"},
           {"field" : "field2","value": "4"},
           {"field" : "field3","value" : "5"}
          ]

The desired output format is as follows:

var result = {
              "feature": "test",
              "filter": {
                 "and": [
                          {
                           "or" : [
                                    {"field": "field1","value": "1"},
                                    {"field": "field1", "value": "2"}
                                  ]                      
                          },
                          {
                            "or" : [
                                     {"field": "field2","value": "3"},
                                     { "field": "field2","value": "4"},
                                   ]                      
                          },
                          {  "field": "field3", "value": "5"}
                  ]
              } 
}

// The method I attempted

filterObj.filter.and.or(...obj) ;// Does not work 


I need to group the elements based on their field values and then insert them into the "or" array of objects if the field values match. Otherwise, they should be directly added to the "and" array of objects.

Any assistance would be greatly appreciated.

Answer №1

  • Combine the filter.and and obj array into a single array.
  • Perform a reduce operation on the combined array.
  • Initialize an accumulator object with each unique field as a key.
  • If the key already exists in the accumulator and has an or property, append the current object to the existing or array.
  • If the key exists but does not have an or property, create a new array containing the existing object in the accumulator and the current object being processed.
  • If the key does not exist in the accumulator, add the key and set it to the current object.
  • Finally, utilize Object.values() method on the resulting object to extract the final and array.

let 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"}];

const merged = obj.concat(filterObj.filter.and || []).reduce((r, o) => {
  if(r[o.field] && r[o.field].or) 
    r[o.field].or.push(o);
  else if(r[o.field])
    r[o.field] = { or: [r[o.field], o] }
  else
    r[o.field] = o;
 return r;
}, {})

const filter = { and: Object.values(merged) },
      { feature } = filterObj;

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Are there any Java alternatives comparable to PHP arrays with non-numeric keys?

How can we convert this PHP array to Java? HashMap<String, String> user = new HashMap<>(); user.put("name", "John"); user.put("email", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="92f8fdfafcd2fff3fbfebcf1fdff" ...

How can React.Js and Typescript be used to extract information from JSON files?

Hi there! I've been working with MongoDB, Mongoose, and React.Js for my project. One of the features I have is a page where users can view posts. When making a fetch request to the backend, I receive JSON data in response: { "post" ...

Alter the CSS of a <div> element upon clicking on it

Is there a way to dynamically adjust the width and height of this div element after it is clicked, essentially treating it like a button? The current HTML structure is as follows: <div class="sq" onclick="main.function();"> ... </div> Below ...

When using the push() method in JavaScript to add a string to an array, the result is coming back

Here is an example input: { "algorithm_run": "mean: 07/02/2018 02:38:09F1 (Mhz) mean", "id": 12, "parameter": "F1 (Mhz) mean", "runs": "2017-09-19 15:41:00(0:00:59.350000)", "start_time": "2017-09-19 15:41:00", "value": 13.56298395 ...

Generating a torus graph in three.js can be a visually stunning and

I'm attempting to design a unique torus graph showcasing different colored segments with varying widths based on data size, essentially a more visually appealing version of a pie chart. Would it be feasible to achieve this using torus geometry, or wo ...

Three.js - The variable "i" in question is not defined and has caused an Uncaught

I'm currently immersed in a project using three.js with the assistance of the parcel bundler. Everything seems to be functioning perfectly on my local setup. However, upon attempting to deploy it on Netlify, I encounter the following error: Uncaught ...

Tips for implementing a nested ng-repeat with nested JSON array data triggered by a button click

Assuming I have assigned the following JSON data to $scope.people: [ { "personId": 1, "name": "Thomas", "age": 39, "friends": [ { "friendId": 1, "nickName": "Lefty" ...

Is there a way to access the current $sce from a controller?

One way to access the current $scope outside of a controller is by using the following code: var $scope = angular.element('[ng-controller=ProductCtrl]').scope(); Is there a way to retrieve the $sce of the current controller? ...

How to Implement Drupal.behaviors for Specific Pages?

Currently, I have a module that showcases an alert to users within a block. For those interested, you can find my code on GitHub here: https://github.com/kevinquillen/User-Alerts If you would like more information about the module and its functionality, ...

`Is there a way to choose several radio buttons with varying names using just one label?`

Is there a way to choose multiple radio buttons with different names using just one label? Here's an example of what I'm attempting to accomplish... <input id="1A" type="radio" name="first" value="A">firstA<br> <input id="1B" typ ...

Discovering additional element information while utilizing the 'Sortable' feature

My Current Objective: In my setup, I have a 'calendar' comprising 5 columns, each column containing 5 separate divs known as timeslots. The main purpose here is to show appointments in these specific timeslots and utilize JQuery's Sortable ...

Methods to verify if an array contains a particular string within a PUG template

I'm currently working with NodeJS using Express and the PUG view engine. My goal is to determine whether an array includes a specific string. I've experimented with JavaScript's built-in methods like: array.includes(str) array.indexOf(str) ...

ways to modify hash URLs using JavaScript

I am looking to add separate hash links for my Facebook and Instagram social media pages. I also want to change the text color to blue for Facebook and yellow for Instagram. How can I achieve this using JavaScript? let socialMediaData = [{ s_media: &apo ...

Tips for providing a directory as the source in Mirth Connect version 2.2.1

I am currently using Mirth Connect version 2.2.1. I am in the process of creating a channel where the source input is a directory with multiple subfolders, each containing files. The issue I am facing is that the source can only read files placed in the pa ...

Three parameters determine the shape of a Numpy ndarray

I'm having trouble understanding the shape of an ndarray when 3 parameters are provided: For instance, what distinguishes between: np.zeros((2, 1, 3)) array([[[ 0., 0., 0.]], [[ 0., 0., 0.]]]) and: np.zeros((1, 2, 3)) array([[[ 0., 0. ...

Ensure the most recently expanded item appears at the top of the TreeView by updating to Mui version

I'm working on a feature where I want to scroll the expanded TreeItem to the top when it has children and is clicked on for expansion. Any suggestions on how to make this happen? ...

Unable to retrieve value - angularJS

An AngularJS application has been developed to dynamically display specific values in an HTML table. The table consists of six columns, where three (Work Name, Team Name, Place Name) are fixed statically, and the remaining three columns (Service One, Servi ...

Supabase's newly uploaded audio blobs are experiencing difficulties when it comes to

I've integrated Supabase storage for storing audio blobs. After retrieving the blob from an API call, it is uploaded successfully to the storage bucket. However, when attempting to play the audio file, nothing happens and the duration shows as 0:00. S ...

Instead of logging the JSON file in the console, download it using $.getJson()

Is there a method to download a json file without using jQuery's $.getJSON() and having to log the callback function's argument? I would like to avoid manually typing it from the console.log due to its length. Is there an option to print it, eve ...

Transmitting Arrays between View and Controller in the MVC Framework

I am currently attempting to transfer the values from the view to the controller var ParamAliasArray = new Object(); for (var i = 1; i <= 1; i++) { ParamAliasArray[i] = $("#txtParamAlias" + i).val(); } var ...