Combining several objects within an array into a single object based on a specific key value pair utilizing javascript

In my grid, I have a dynamically generated array based on filtered values like the example shown below.

    [
        {
            attributeId: 145,
            attributeName: "Status",
            filterOperator: "Is equal to",
            filterValue: "Active",
            SortBy: ""
        },
        {
            attributeId: 161,
            attributeName: "Code",
            filterOperator: "Contains",
            filterValue: "22",
            SortBy: ""
        },
        {
            attributeId: 161,
            attributeName: "Code",
            filterOperator: "",
            filterValue: "",
            SortBy: "ASC"
        }
    ]

In this array, there are two objects with the same 'attributeId', but one contains SortBy details while the other contains filtering details. I want to merge these two objects into one, resulting in:

    {
            attributeId: 161,
            attributeName: "Code",
            filterOperator: "Contains",
            filterValue: "22",
            SortBy: "ASC"
    }

If the objects are identical, duplicates can be removed using the following code:

this.columnList = Object.values(this.columnList.reduce((acc, cur) => Object.assign(acc, {
  [cur.attributeName]: cur
}), {}));

The 'columnList' is the name of the array. Any suggestions or insights would be greatly appreciated. Thank you!

Answer №1

To condense the array and group it by the attributeId, you can use a reduction method. If the attributeId is already present in the accumulator, iterate through the object's entries and update each value that is not empty. If the attributeId is not present, add it to the accumulator.

const data=[{attributeId:145,attributeName:"Status",filterOperator:"Is equal to",filterValue:"Active",SortBy:""},{attributeId:161,attributeName:"Code",filterOperator:"Contains",filterValue:"22",SortBy:""},{attributeId:161,attributeName:"Code",filterOperator:"",filterValue:"",SortBy:"ASC"}];

const condensedData = data.reduce((acc, obj) => {
  const { attributeId, ...rest } = obj;
  
  if (!acc[attributeId]) 
    acc[attributeId] = { ...obj }
  else 
  {
    Object.entries(rest).forEach(([key, value]) => {
      if (value)
        acc[attributeId][key] = value
    })
  }
  
  return acc
}, {})

console.log(Object.values(condensedData))

Answer №2

Streamlining the code:

var data = [ { attributeId: 145, attributeName: "Status", filterOperator: "Is equal to", filterValue: "Active", SortBy: "" }, { attributeId: 161, attributeName: "Code", filterOperator: "", filterValue: "22", SortBy: "" }, { attributeId: 161, attributeName: "New Code", filterOperator: "Contains", filterValue: "", SortBy: "ASC" } ];

let getResolvedData = (array) => {
  return Object.values(array.reduce((acc, {attributeId, ...rest})=>{
   acc[attributeId] = acc[attributeId] || {attributeId};
   Object.entries(rest).forEach(([key,value])=>{
      if(acc[attributeId][key] && value) acc[attributeId][key] = value
      if(!acc[attributeId][key]) acc[attributeId][key] = value;
   })
   return acc;
},{});
}

console.log(getResolvedData(data));

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

How can I arrange individual events in agendaWeek view on FullCalendar.io and then merge them all into one line?

I am using Fullcalendar.io version 2 When I switch to the agendaWeek mode, all my events are displayed on one line in each day square. As a result, the more events I have, the thinner the event blocks become. Is there a way for me to display only one eve ...

Unable to access 'this' within a custom operator in RxJs

I developed a unique operator that utilizes the this keyword, but I am encountering an issue where it always returns undefined. Even though I used bind to pass this into the function. My special operator function shouldLoadNewOptimizationData() { retu ...

Using JavaScript to send form input in the form of a 2D array through AJAX

I am currently working on a form that looks like this: <form name="chat" id="chat" action="" onsubmit="sendMessage()"> <a name="chat">&nbsp;</a> <input type="text" name="chat" id="chat" size="38" maxlength="50" vertical-align="m ...

Navigating through a large array list that contains both arrays and objects in Typescript:

I have an array containing arrays of objects, each with at least 10 properties. My goal is to extract and store only the ids of these objects in the same order. Here is the code I have written for this task: Here is the structure of my data: organisationC ...

Interface for dynamic objects in Typescript

I am currently using JavaScript to create an object and would like to include an interface for the data: JavaScript: const childGroups: Children = {}; childGroups.children = []; // Adding some data childGroups.children.push(children); Interface: ...

Interactive Animation featuring Interactive Pop-up Boxes

I am facing an issue with the 'zoomIn' animation where the background: rgba(0, 0, 0, 0.5); is not present when the popup box appears. I want the background to be there from the start of the animation. Additionally, after clicking the Submit butt ...

What is the best way to conceal a website's URL?

Is it possible to hide the actual URL some.otherdomain.com and show only domain.com to visitors of my website? I am looking for a way to mask the URL, perhaps through .htaccess or javascript. Is there any solution available? ...

Guide to creating an autocomplete search bar in CodeIgniter

I've been working on creating an autocomplete search field in CodeIgniter, but I'm encountering some issues. Despite setting a limit of 10 results, every time I input a character, the list keeps expanding endlessly as shown in the screenshots bel ...

Retrieving information from a JSON file results in the value of "undefined"

Currently, I am working on a data visualization project in React using Recharts. The data is sourced from a static JSON file. My aim is to enable users to click on the Bar Chart and have the selected value passed to the app. Subsequently, this value should ...

Dynamically resizable overlapping divs in CSS

Encountering an issue with a div element on a webpage. When resizing the browser page in Chrome, the div overlaps other elements and part of it is hidden. However, in IE, the height:auto property behaves as expected without any overlapping. I have attempte ...

Unable to proceed with iteration

I am encountering an issue with the ng-repeat directive while working on it. As a beginner, I am struggling to resolve it on my own. var myModule = angular.module("myFirst",[]); myModule.controller("cont", function($scope){ var employees = [ {name: "Ma ...

Converting a two-dimensional array into a collection of sparse arrays

How can I transform the array x=[[3,1],[2,2]] into x[3][1]=1 and x[2][2]=1? Is there a way to make this code functional for arrays such as x=[[3,1],[2,12],[3,3]]? ...

What are the steps for implementing timezone-js?

I found a project on GitHub that claims to convert one timezone to another. I've been trying to get it to work without success. After downloading and extracting the files, I created an HTML file with the following code: <html xmlns="http://www.w3. ...

What is the best way to search for a specific letter in a character array using a user input?

Asks the user to enter a single letter. This function checks if the input is a valid letter or if the user wants to quit by typing '!' character. It will continue to prompt for letters until '!' is entered, at which point it will print ...

Struggling with implementing ajax functions in Javascript to interact with mysql databases

I am facing some challenges in integrating an ajax function into my Javascript timer in order to add an item to the database every time the timer restarts. I came across a helpful resource at , but I'm struggling to implement it into my code. Any assi ...

Using JavaScript, you can filter an array of objects based on a specific search input

I am in the process of implementing a filtering feature for a list using React, but surprisingly, I haven't been able to find any useful resources online to guide me through this common task. Currently, I have an array of users that I need to filter ...

What options are available for managing state in angularjs, similar to Redux?

Currently, I'm involved in an extensive project where we are developing a highly interactive Dashboard. This platform allows users to visualize and analyze various data sets through charts, tables, and more. In order to enhance user experience, we ha ...

What is causing the issue with the code `exports = { z: function() {} };` not functioning as intended?

Script A exports = { z: function() { console.log('aZ'); } }; Script Main require('./a').z(); // error Have you ever wondered why require('./a') ends up returning an empty object? ...

Conceal the information beneath a see-through fixed navigation bar when scrolling downward

the issue: I am facing a challenge with my transparent fixed navbar that has a margin-top gap. The content below the navbar needs to be positioned under it while scrolling down, but the background of the page is a dynamic slideshow of various images. This ...

Can media queries styles be applied to a window of random size using JavaScript?

Can JavaScript be used to apply media queries style based on random window sizes? I have 5 buttons that I want to switch styles for using JavaScript according to the media queries defined in my CSS stylesheet. Is there a method to achieve this? ...