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

Ensure the http request is finished before loading the template

When my template loads first, the http request is fired. Because of this, when I load the page for the first time, it shows a 404 image src not found error in the console. However, after a few milliseconds, the data successfully loads. After researching a ...

Leveraging React Native to retrieve information from a promise in JSON format

After successfully fetching the JSON data, I now have an array. My question is how can I utilize the elements within this array in a React Native environment? Below is my current approach: export default function display() { const fetching = async() => ...

Exploring the Power of GraphQL Args in Mutation Operations

Currently, I am in the process of developing a blog service using express and apollo-express in conjunction with mongodb (mongoose). While implementing mutation queries, I have encountered difficulties in accessing the arguments of a mutation query. I am ...

Tips for enhancing the color saturations of cells that overlap in an HTML table

My goal is to enhance the color of overlapping cells in my HTML tables. For instance, when I click on cell 2, the .nextAll(':lt(5)') method will change the class of the next 4 cells. https://i.stack.imgur.com/mwv8x.png Next, clicking on cell 3 ...

Automatically calculate the multiplication of a number by 10 in React JS within the State

In this scenario, I am looking for assistance in creating a functionality where the user can adjust numbers in an input box and see the result of that number multiplied by 10 in a nearby span element. However, I am encountering issues with fetching the des ...

Using Angular's built-in dependency injection with the $resource factory allows for

Question regarding Dependency Injection on factory resource: As far as I know, the following example is the recommended approach for injecting dependencies in Angular1: angular.module('myApp').factory('Resource', Resource); Resource. ...

What is the best way to keep track of a checkbox's value after unchecking it and then returning to the same slide?

Issue: By default, the checkbox is always set to true in the backend code. Even if I uncheck it using JavaScript, the value remains as true when switching between slides. Desired Outcome: If I uncheck the checkbox, the updated value should be saved so tha ...

What is the method for performing a spelling check on every property within an array of Objects?

I'm working on a program that takes a user input as an argument and then searches for a similar match in an array of objects. The array of objects is retrieved from a database. When the user inputs a name, the search criteria should find objects with ...

Scroll through the div to quickly find the relevant content

I have implemented the following HTML structure: <div style="height:200px;overflow-y:scroll;"> <table>.....</table> </div> By using this setup, I am aiming to replicate the functionality of an expanded <select> control wit ...

Javascript - readjust weight distribution accordingly when a weight is removed

I am in possession of a dataset that shows the proportion of each test contributing to the final grade. In cases where a student has missed one or more tests, the weight is redistributed accordingly among the tests they did take. I want to determine how ...

The function(result) is triggered when an http.get request is made

Can anyone help me figure out why my function is jumping after completing the request? It seems to be skipping over .then(function(result){ }. I suspect that the issue might be related to the <a> element with an onclick attribute containing an href ...

Angular does not always interpret the value returned from a Promise.all call

One of the challenges I'm facing is related to the structure of my controller: controller.things = ['a', 'b', 'c']; controller.loading = true; controller.responses = []; controller.handlePromises = function(){ var pr ...

Nuxt - Vue - Utilizing middleware on a layout in a few simple steps

Recently, I developed a middleware for authentication in my Nuxt application and now I want to utilize it within a layout. However, when trying to call the middleware using the following code: export default { middleware: 'auth', I encounte ...

Arrange objects in an array according to the order specified in another array

Here is my array of car makes: const makes = [ {id: "4", name: "Audi"}, {id: "5", name: "Bmw"}, {id: "6", name: "Porsche"}, {id: "31", name: "Seat"}, {id: "32", name: "Skoda"}, {id: "36", name: "Toyota"}, {id: "38", name: "Volkswagen"} ] Now, I want to o ...

Can the conventional HTML context menu be swapped out for a link context menu instead?

Currently, I am working on developing a custom linkbox component that is similar to the one found on this page: Here is an example of the code: export const Linkbox = ({}) => { const linkRef = useRef(null); return ( // eslint-disable-next-l ...

Can anyone provide a method for obtaining a date that is x days earlier through date arithmetic?

Is there a method to obtain the date from 63 days ago with only day, month, and year information needed, excluding hours, minutes, and seconds? I am aware that one can calculate Date object - Date object, but I am curious if it is feasible to derive a dat ...

Toggle jQuery to hide a div and update its CSS styling

There is an anchor with the class of "hide-btn1" that I want to trigger a series of actions when clicked: The rcol-content should hide and the text should change from Hide to Show The #container width needs to increase to 2038px The table.status-table wi ...

Utilizing object UUID keys to associate products in VueJS

Hey there, I've gone ahead and created an object with UUIDs but now I'm looking for a way to link these UUIDs to specific items. It seems like there needs to be some separation between the UUID and the rest of the object, however, my main issue i ...

Ensuring the website retains the user's chosen theme upon reloading

I have been developing a ToDo App using MongoDB, EJS, and Node JS. My current challenge involves implementing a theme changer button that successfully changes colors when clicked. However, whenever a new item is added to the database, the page reloads caus ...

Guide on uploading multipart career-form data with file paths and validation in CodeIgniter with the help of AJAX

I am facing an issue while attempting to insert job form data with file uploading and validation in PHP CodeIgniter via AJAX. The code I am using is provided below, but unfortunately, it's not functioning as expected. Can anyone help me figure out how ...