JavaScript - Combine objects in an array with multiple keys

I am looking to transform a JavaScript array by merging elements with the same values for specified properties into one object. The other properties for these merged elements should be kept as either a comma-separated string, JSON string, or an array. Here is the initial array:

[
    {
        "language" : "english",
        "type" : "a",
        "value" : "value1"
    },
    {
        "language" : "english",
        "type" : "a",
        "value" : "value2"
    },
    {
        "language" : "english",
        "type" : "b",
        "value" : "value3"
    },  
    {
        "language" : "spanish",
        "type" : "a",
        "value" : "valor1"
    }
]

The desired transformed array looks like this:

[
    {
        "language" : "english",
        "type" : "a",
        "value" : ["value1" , "value2"]
    },
    {
        "language" : "english",
        "type" : "b",
        "value" : "value3"
    },  
    {
        "language" : "spanish",
        "type" : "a",
        "value" : "valor1"
    }
]

While I have attempted iterating and filtering through the array and performing upsert operations on the objects, I am curious if there is a more elegant solution available.

Additionally, suggestions related to EcmaScript6 or any other JavaScript libraries are appreciated.

var originalArray = [
{
"language" : "english",
"type" : "a",
"value" : "value1"
},
{
"language" : "english",
"type" : "a",
"value" : "value2"
},
{
"language" : "english",
"type" : "b",
"value" : "value3"
},
{
"language" : "spanish",
"type" : "a",
"value" : "valor1"
}
];

var resultingArray = [];

// iterate through the original array
$.each(originalArray, function(i, val) {
  // apply filter on key properties (i.e. language and type)
  var result = resultingArray.filter(function( obj ) {
    return (obj.language === val.language && obj.type === val.type);
  });
  // if a record exists, update its value
  if (result.length === 1) {  
    result[0].value += (", " + val.value);
  } 
  // else, add value
  else if (result.length === 0) {
    resultingArray.push(val);
  }
  // if multiple rows exist with same key property values...
  else {
    alert("Too many records with language '" + val.language + "' and type '" + val.type + "'");
  }
});

console.log(JSON.stringify(resultingArray));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Answer №1

Is this the solution you were looking for?

var mainData = [
    {
        "language": "english",
        "type": "a",
        "value": "value1"
    },
    {
        "language": "english",
        "type": "a",
        "value": "value2"
    },
    {
        "language": "english",
        "type": "b",
        "value": "value3"
    },
    {
        "language": "spanish",
        "type": "a",
        "value": "valor1"
    }
];

var updatedData = [];
mainData.forEach(function(entry, key) {
    if (updatedData.length === 0) {
        updatedData.push(entry);
    } else {
        var existingIndex = -1;
        updatedData.forEach(function(existingEntry, existingKey) {
            if (entry.language === existingEntry.language && entry.type === existingEntry.type) {
                existingIndex = existingKey;
            }
        });

        if (existingIndex !== -1) {
            var oldVal = updatedData[existingIndex].value;

            if (typeof(oldVal).toString() === 'string') {
                updatedData[existingIndex].value = [oldVal, entry.value];
            }
        } else {
            updatedData.push(entry);
        }
    }
});
console.log(updatedData);

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

Calculate and Organize the Common Elements in an Array

Here is an example schema structure: module.exports = function(connection, mongoose) { // var autoIncrement = require('mongoose-auto-increment'); var UsersSchema = new mongoose.Schema({ first_name: String, last_name: String, ...

Is it possible to vertically center a child div within its parent container using JavaScript when the page loads without explicitly setting its position?

Using JavaScript to vertically center a child div within a fluid container involves calculating the height of both elements and positioning the child div accordingly. However, one issue faced is that the position is not set when the page loads. To solve ...

Access scope variable in AngularJs from another scope variable

I am currently working on a basic app for demonstration purposes, and I have encountered the following issue: I have two objects in my controller (credentials and authServer) and I want to access the properties of credentials within the authServer object. ...

Angular - How child components can communicate with their parent components

I'm struggling to understand how to communicate between components and services. :( Even though I've read and tried a lot, some examples work but I still don't grasp why (?). My goal is to have one parent and two child components: dashboa ...

Is the × symbol added from JavaScript not able to be clicked on?

In my javascript code, I have added HTML content dynamically using the following method: var response = { message: "sample messsage" }; $('#main-content').append( '<div class="alert alert-danger alert-dismissable">'+ & ...

Upgrade to a more stable configuration version for Nodemailer as the current configuration is not supported. Consider down

I'm currently utilizing Nodemailer version 2.6.4 with Node version 6.9.1 var nodemailer = require("nodemailer"); var wellknown = require('nodemailer-wellknown'); var transporter = nodemailer.createTransport("SMTP",{ service: "yahoo", ...

Tips for aligning meshes to the left and ensuring responsiveness in three.js

Currently working on a website using three.js, I'm facing an issue where I can't seem to align and make the mesh responsive simultaneously. My current approach to alignment is: cube.position.x = -20 However, when I try resizing the window, the m ...

Troubleshooting the issue of React not properly loading dynamically fetched HTML data using dangerouslySetInnerHTML

I am facing a challenge with dynamically loading HTML format data using dangerouslySetInnerHTML. Even though I am utilizing the axios plugin for AJAX API calls, the content is not being compiled and displayed as expected in the DOM. Strangely, when I hardc ...

Generate all possible arrangements of zeros and ones in a two-dimensional matrix with dimensions of n by n

Looking to create a function that will generate an array of all possible 2D arrays consisting of 0s and 1s in JavaScript within a square 2D array. Essentially, this is similar to the question posed here: Make every possible combination in 2D array However ...

issue arising from unique style identifiers in FireFox while making changes to styles via document.styleSheets

While experimenting with altering some stylesheets using JavaScript, I encountered an interesting issue: When attempting to set an attribute on a style rule in Firefox and the property is one of their proprietary ones, it fails silently. To demonstrate th ...

Encountering a 404 error when attempting to make an Axios post request

Utilizing Axios for fetching data from my backend endpoint has been resulting in a 404 error. Oddly enough, when I manually enter the URI provided in the error message into the browser, it connects successfully and returns an empty object as expected. Her ...

Utilizing Angular Filters to Assign Values to an Object within a Controller

I have a JSON example with multiple records, assuming that each name is unique. I am looking to filter out an object by name in the controller to avoid constant iteration through all the records using ng-repeat in my HTML. { "records": [ { "Name" : ...

How can I incorporate dynamic data to draw and showcase graphs on my website using PHP?

I am currently working on a project that requires displaying a graph showing the profit of users per day. Currently, I have implemented code to display a static graph on my page. <script type="text/javascript" src="https://www.google.com/jsapi">< ...

Exclude the footer from the index.html file by configuring it in the docusaurus.config.js file

From what I understand, the docusuarus.config.js file is responsible for translating specified information into HTML to construct your website. This translated information is then directed to the 'index.html' file. However, I am encountering an ...

Encountering a `Syntax Error` in a Jade view

I am attempting to create a basic chat application using the simple jade view engine with express. Upon running my app, I encountered a syntax error in the following view code, even though it seems quite straightforward. extends layout block scrip ...

Troubleshooting "Nodejs Socket hang up & ECONNRESET" when sending an HTTP post request from a Meteor app to a Node.js

Utilizing a node server for managing all push notification services like GCM and APN. I have 2 separate servers in operation - one hosting Meteor and the other running Node.JS to handle push notifications. (Both servers are distinct) The primary applicat ...

Saving MongoDB query results to a file using the built-in Node.js driver

I have been attempting to save the output of a MongoDB query to a file using the native Node.js driver. Below is my code (which I found on this post: Writing files in Node.js): var query = require('./queries.js'); var fs = require('fs' ...

The calender icon in Bootstrap4 datepicker input is unresponsive to clicks

template.html {% block content %} {% endblock %} <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin= ...

React cannot be utilized directly within HTML code

I am looking to incorporate React directly into my HTML without the need for setting up a dedicated React environment. While I can see the test suite in the browser, my React app fails to load. Below is the content of my script.js file: I have commented ...

How to get the total number of rows/records in a JSON store using ExtJS?

My dilemma involves a JSON store that provides data in JSON format. I am currently attempting to determine the number of rows or records in the JSON string. However, when utilizing the store.getCount() function, it consistently returns 0. Strangely, the ...