Ways to combine extensive value within an array containing various objects

I am working with an array of objects and I need to merge all the values of params within each object into a single object.

Array [
  Object {
    "key": "This week",
    "params": Object {
      "thisWeekfilterDistance": [Function anonymous],
      "thisWeekSearch": [Function anonymous],
      "thisWeektoggleFilter": [Function anonymous],
      "thisWeektoggleRangeFilter": [Function anonymous],
    },
    "routeName": "This week",
  },
  Object {
    "key": "Coming soon",
    "params": Object {
      "soonfilterDistance": [Function anonymous],
      "soonSearch": [Function anonymous],
      "soontoggleFilter": [Function anonymous],
      "soontoggleRangeFilter": [Function anonymous],
    },
    "routeName": "Coming soon",
  },
  Object {
    "key": "Festivals",
    "params": Object {
      "festivalfilterDistance": [Function anonymous],
      "festivalSearch": [Function anonymous],
      "festivaltoggleFilter": [Function anonymous],
      "festivaltoggleRangeFilter": [Function anonymous],
    },
    "routeName": "Festivals",
  },
]

I have attempted the following:

for (var i = 0; i < 3; i++) {
        if (typeof arr[i].params !== 'undefined') {
            //console.log(arr[i].params);
            test = arr[i].params;
        }
    }

or


for (var i = 0; i < 3; i++) {
   arr[i].param.reduce(function(result, current) {
     return Object.assign(result, current);
   }, {})
}

However, I am struggling to figure out how to consolidate these results into a single object containing all object params.

The desired outcome is:

{
      "thisWeekfilterDistance": [Function anonymous],
      "thisWeekSearch": [Function anonymous],
      "thisWeektoggleFilter": [Function anonymous],
      "thisWeektoggleRangeFilter": [Function anonymous],
      "soonfilterDistance": [Function anonymous],
      "soonSearch": [Function anonymous],
      "soontoggleFilter": [Function anonymous],
      "soontoggleRangeFilter": [Function anonymous],
      "festivalfilterDistance": [Function anonymous],
      "festivalSearch": [Function anonymous],
      "festivaltoggleFilter": [Function anonymous],
      "festivaltoggleRangeFilter": [Function anonymous],
}


Thank you.

Answer №1

To retrieve an array of parameters, you can utilize the map method. Then, merge these objects into a single object using Object.assign():

const input = [{"key":"This week","params":{"thisWeekfilterDistance":_=>{},"thisWeekSearch":_=>{},"thisWeektoggleFilter":_=>{},"thisWeektoggleRangeFilter":_=>{},},"routeName":"This week",},{"key":"Upcoming","params":{"soonfilterDistance":_=>{},"soonSearch":_=>{},"soontoggleFilter":_=>{},"soontoggleRangeFilter":_=>{},},"routeName":"Upcoming",},{"key":"Festivals","params":{"festivalfilterDistance":_=>{},"festivalSearch":_=>{},"festivaltoggleFilter":_=>{},"festivaltoggleRangeFilter":_=>{},},"routeName":"Festivals",},]

const output = Object.assign({}, ...input.map(a => a.params))
console.log(output)

Answer №2

You should utilize Array#reduce on a direct array instead of using array object parameters

var arr = [{ "key": "This week", "params":  { "thisWeekfilterDistance": "[Function anonymous]", "thisWeekSearch": "[Function anonymous]", "thisWeektoggleFilter": "[Function anonymous]", "thisWeektoggleRangeFilter": "[Function anonymous]", }, "routeName": "This week", }, { "key": "Upcoming", "params":  { "soonfilterDistance": "[Function anonymous]", "soonSearch": "[Function anonymous]", "soontoggleFilter": "[Function anonymous]", "soontoggleRangeFilter": "[Function anonymous]", }, "routeName": "Upcoming", }, { "key": "Festivals", "params":  { "festivalfilterDistance": "[Function anonymous]", "festivalSearch": "[Function anonymous]", "festivaltoggleFilter": "[Function anonymous]", "festivaltoggleRangeFilter": "[Function anonymous]", }, "routeName": "Festivals", }, ]

var res = arr.reduce((a,b) => Object.assign(a,b.params),{})

console.log(res)

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

What could be causing the `unstable_Profiler` to not function properly in production mode?

Encountering a problem with unstable_Profiler in my React-Native project where the onRender callback is being ignored, but only in production mode. No errors are being thrown and everything renders correctly. I followed the advice from this article: I tes ...

Tips for sending an Object within a multipart/form-data request in Angular without the need for converting it to a string

To successfully pass the object in a "multipart/form-data" request for downstream application (Java Spring) to receive it as a List of custom class objects, I am working on handling metadata objects that contain only key and value pairs. Within the Angula ...

Tips for preserving login status even after the browser is shut down with the help of JavaScript

I need help with maintaining a user session in my chat application even when the browser is closed. After users log in for the first time, I want their credentials to be remembered by the browser (I'm currently using local storage). How can I ensure ...

Attempting to monitor the frequency of calls to a JavaScript function

let totalEnteredCount = 0; function totalEntered(field){ if(field.value != '') { totalEnteredCount++; } alert(Counter); if(totalEnteredCount == 3) { var InitialVelocity = document.getElementById("IVUnit").value; var FinalVelocity = do ...

Unusual issue with jQuery function failing to detect click events

As I delve into my first jQuery function, the primary goal is to assign a form to the function. Upon clicking the submit button, it should perform validation on each :input field within the function. The form is set as the selector for the function: $("f ...

Using arrow functions in Typescript e6 allows for the utilization of Array.groupBy

I'm attempting to transform a method into a generic method for use with arrow functions in JavaScript, but I'm struggling to determine the correct way to do so. groupBy: <Map>(predicate: (item: T) => Map[]) => Map[]; Array.prototype ...

Having trouble transmitting JSON data to an Express server through the browser

I have set up two servers: the first one is for frontend (localhost:7200), and the second one is for backend (localhost:7300). There is a test request made by the frontend to the backend on the route '/test'. The issue arises when I attempt to s ...

Failure to respond to dual part form by RemoveClass

Currently, I am utilizing jQuery to visually control a form. The issue arises when trying to remove classes from the first part of the form using removeClass. While this works initially, upon clicking the button to advance to the second part of the form, t ...

What causes an error when trying to access with the member access operator?

When dealing with object properties in the code snippet below, an error is thrown when trying to access the object using the Member Access. Why does this happen? var d = {a: 10, b: 20, c:30}; var keys = Object.getOwnPropertyNames(d); ...

Reveal or Conceal Information Depending on Cookie Status

Below is the Jquery code I am using: $("#tool").click(function() { $(".chelp").slideToggle(); $("wrapper").animate({ opacity: 1.0 },200).slideToggle(200, function() { $("#tool img").toggle(); }); }); When the #tool img is clicked, bot ...

What is causing my grayscale function to only impact part of the canvas?

As a beginner programmer, I have been experimenting with creating a grayscale function in JavaScript for practice. This is the code I have come up with: <canvas width='400' height='400'></canvas> <script> var can ...

The type 'Navigator' does not have the property 'userAgentData' in its definition

Since I'm looking to minimize the information provided by navigator.userAgent, I decided to migrate to User-Agent Client Hints. However, I've encountered an error while attempting to do so: https://i.stack.imgur.com/lgIl7.png Could someone plea ...

Animate my banner images only after they have fully loaded using Jquery

I recently came across a banner image slideshow in jQuery, but it seems to be animating even before the images are fully loaded. This results in the slideshow displaying image descriptions without the actual images themselves. Can anyone help me modify th ...

Utilize VueJS to pass back iteration values using a custom node extension

Hey there! I'm currently working on a Vue app that generates a color palette based on a key color. The palette consists of 2 lighter shades and 2 darker shades of the key color. To achieve this, I have set up an input field where users can enter a hex ...

Click on a specific button within a DataTable row

I am working with a dataTable that fetches data from the database using Jquery. In each row, there are two buttons for accepting or rejecting something. My goal is to make the accept button disappear when rejecting and vice versa. public function displayT ...

Toggle the Bootstrap navbar class based on the current scroll position

I'm currently working on the development of a website that includes a feature where a static navbar transforms into a fixed navbar after scrolling down 500px. The transition from "navbar-static-top" to "navbar-fixed-top" is functioning properly. Howev ...

Having trouble printing a section of a webpage after making CSS adjustments

When trying to print part of a page, I used the following method. It successfully prints that portion of the page, however, it does not preserve the CSS effects. <body> <h1><b><center>This is a test page for printing</center&g ...

typescript is failing to update CSSRule with the newly assigned background-color value

I am currently working on dynamically changing the CSS style (specifically background-color) for certain text on a webpage. To achieve this, I have been attempting to modify CSSRule by accessing the desired CSSRule based on selectedText. Here is the code s ...

What strategies can I use to streamline this array update function code?

Looking to simplify my updated array function. The update function involves updating and comparing values in an array. The comparison will be done within the fruit_temp. For example, data in fruit_temp's fruit_db_id corresponds to an existing id in th ...

Updating chart.js data seems to be presenting some challenges

Need help fetching data with an AJAX request to update chart.js. The AJAX request is working fine, but the response doesn't update the chart. This is how I fetch the data: <script type="text/javascript"> $(document).ready(function(){ $("#da ...