Combine an array of objects into a single unique object in JavaScript

I'm trying to merge an array of objects into a single object, ensuring that each value is distinct. However, my current code isn't producing the output I want. Can someone assist me with this?

Sample Input: 
    [{
        "obj1" : "value1",
        "obj2" : ["abc", "def"],
        "obj3" : ["ghi"],
        "obj4" : "value4",
    },
    {
        "obj1" : "value2",
        "obj2" : ["abc", "mno"],
        "obj3" : ["klm"],
        "obj4" : "value4",
    }]


Desired Output:
{
    "obj1" : ["value1","value2"]
    "obj2" : ["abc", "def","mno"],
    "obj3" : ["ghi","klm"],
    "obj4" : ["value4"]
}

My Current Code:
const result = filterData.reduce((a,c) => (Object.keys(c).map(k => a[k] = [...a[k] || [], c[k]]), a), {})

Answer №1

To combine multiple objects into a single object within an array, you can utilize array#reduce. For obtaining unique values, the Set method comes in handy.

const data = [{ "obj1" : "value1", "obj2" : ["abc", "def"], "obj3" : ["ghi"], "obj4" : "value4", }, { "obj1" : "value2", "obj2" : ["abc", "mno"], "obj3" : ["klm"], "obj4" : "value4", }],
      result = data.reduce((r,o) => {
        Object.keys(o).forEach(k => {
          r[k] = [...new Set((r[k] || []).concat(o[k]))];
        });
        return r;
      },{});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Using lodash helpers, I have crafted a solution to your issue.

const inputData = [{
        "obj1" : "value1",
        "obj2" : ["abc", "def"],
        "obj3" : ["ghi"],
        "obj4" : "value4",
    },
    {
        "obj1" : "value2",
        "obj2" : ["abc", "mno"],
        "obj3" : ["klm"],
        "obj4" : "value4",
    }]
    
function customizer(objValue, srcValue) {
  if (_.isArray(objValue)) {
    return _.union(objValue, srcValue);
  }
}
    
const outputData = inputData.reduce((acc, cur) => {
  const modifiedCur = _.mapValues(cur, function(o) { return typeof o === 'string' ? [o]: o; }); 
  acc = _.mergeWith(acc, modifiedCur, customizer);
  return acc
},{})    
    
console.log(outputData)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

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

Unlocking Secret Data with External JavaScript

Currently, I am focusing on validating user input, specifically the name to ensure it is at least 6 characters long. Although I plan to implement more validation, I am facing an issue with error display. When the JavaScript code is embedded within the HTML ...

The execution of the HTTP request is not happening

As a newcomer to JS and Node, I am attempting to display a JADE view using JSON obtained from a REST API. Everything works perfectly when I run the http.request on its own, but as soon as I introduce modules and rendering statements, the http request funct ...

Deliver either a Promise or a boolean based on the provided parameters, utilizing a default

I have some code that can either return a boolean or a Promise depending on the parameters provided. function setGuid<B extends boolean>(guid: string, shouldValidate?: B): B extends true ? boolean : Promise<boolean> function setGuid(guid: strin ...

Printing keys of objects in an array in AngularJS through iteration

Here is an array of objects that I am attempting to iterate in ng-repeat and print keys, but I am facing some challenges. $scope.directivesInfo = [ {"ngRepeat": {"enter": true, "leave": true, "move": true, "add": false, "remove": false}}, {"ngView ...

What is the Reactjs method for relocating a button from one div to another upon being clicked?

I have organized the buttons inside a div like this: const [state, setstate] = useState([]); getButtonsUsingMap(){ const arr = [1,2,3,4,5]; return arr.map((num) => { return ( <button key={num} className="bu ...

What is the correct way to convert a JArray into a list of strings?

I have a JArray saved in a variable of type object public object Errors { get; } This variable can store either of the following: Errors = {[ { "name": [ "Username &quot;admin&quot; has already been taken." ], ...

Exploring JSON documents one line at a time

What is a more efficient method for parsing a large file filled with individual lines of JSON objects without the need to store each line in a list? ...

Is there a potential memory leak issue with Express.js running on Node.js?

For a basic project, I've been utilizing express with Node.js on a Heroku server. However, after implementing New Relic to monitor memory usage, I noticed a gradual memory leak. To troubleshoot, I removed all custom code and extra Node modules, leavin ...

Vue - making one element's width match another element's width

Trying to dynamically adjust the innermost element's width to match the outermost element's width with Vue: <div id="banner-container" class="row"> <div class="col-xs-12"> <div class="card mb-2"> <div ...

What is the best way to use a generic to reference the value of an object in Typescript?

I've been working on creating a signature for this particular function: export function objToArray(obj){ let result = []; for(const prop of Object.keys(obj)){ result.push(Object.assign({objProp: prop.toString()}, obj[prop])); } ...

Using Node.js to generate PDF documents and send them directly to the response stream

I am currently utilizing PDFKit, a PDF generation library for Node.js, which can be found at pdfkit.org. My goal is to send a PDF as a response to a client. # Save the PDF file to the disk doc.write('output.pdf'); The code provided above saves ...

Tips for calculating the sum of a two-dimensional array

Having two arrays with index values to be summed, the arrays look like: Array ( [0] => Array ( [0] => 7 [1] => 8 ) [1] => Array ( [0] => 6 [1] => 3 ...

The message from the Discord bot is not displayed in an embedded format

When using the code below: message.reply('some reply', { embed: { color: 3447003, description: "A very simple Embed!" } }); } the response from my bot will appear as a regular messa ...

Generating JSON output in Python

For my current project, I have split it into two files - Snapchat.py and test.py In Snapchat.py, the important part of the code is: def add_friend(self, username): """Add user as friend Returns JSON response. Expected messages: Succes ...

Unable to access an HTML element using refs within the render() method

Currently, I am working on developing a graphics editor using ReactJS. One of the main components in my project is the Workspace component. This particular component is responsible for drawing objects on the canvas element. The Workspace component is imple ...

WebGl - texture failed to load

I encountered an error message stating: Uncaught SecurityError: Failed to execute 'texImage2D' on 'WebGLRenderingContext': The cross-origin image at file:///C:/Users/.../img.jpg may not be loaded. var scene, camera, renderer; var ...

Show an error message in a popup window, following a validation error in Laravel

I am facing an issue with displaying error messages in the update modal form. I am using Laravel request for validation and AJAX to submit the form inside a modal. My goal is to show the error message for each field that is inputted incorrectly. However, i ...

Sending an array of text values to a Spring MVC endpoint through Jquery's Ajax functionality

When attempting to pass a list of Strings to an MVC controller using JQuery Ajax, I encountered the No mapping for POST /myUrl/myContext/p error message. Below is my jQuery function: $('#myButton').on('click', function(){ var stri ...

Jackson JSON parser can handle recursive type conversions

I am currently utilizing Jackson to transform a json string into a scala case class instance. Below is the code snippet import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper} import com.fasterxml.jackson.module.scala.DefaultScalaModu ...

Steps to avoid the button being submitted twice

I am facing an issue with two buttons in my code. One button is used to increase a count and the other button is meant to submit the count and move to the next page. The problem is that when I click on the "Proceed" button, it requires two clicks to procee ...