Combine Two Arrays into a JSON Object and Merge Duplicate Key Values without Using ES6 in JavaScript

Seeking a swift javascript solution to merge two arrays with the same length into an array of json objects. In addition, the code should append any errors to the existing .error element. Preferably, the solution should utilize vanilla javascript instead of ES6.

var codes = ["12345", "12345","67890", "67890", "67890","67890","12092", "12092"];

var errors = ["12345 error 1","12345 error 2","67890 error 1","67890 error 2","67890 error 3","67890 error 4","12092 error 1","12092 error 2"];

Desired transformation:

{
    "code": "12345",
    "error": "12345 error 1, 12345 error 2"
},
{
    "code": "67890",
    "error": "67890 error 1, 67890 error 2, 67890 error 3, 67890 error 4, 67890 error 5"
},
{
    "code": "12092",
    "error": "12092 error 1 , 12092 error 2"
}

Answer №1

To combine them, use the map method, then group them together and convert them into an array of objects:

const codes = ["12345", "12345","67890", "67890", "67890","67890","12092", "12092"];
const errors = ["12345 error 1","12345 error 2","67890 error 1","67890 error 2","67890 error 3","67890 error 4","12092 error 1", "12092 error 2"];

const result = Array.from(
    codes.map((code, index) => ({code, errors: errors[index]}))
        .reduce((accumulator, current) => accumulator.set(current.code, (accumulator.get(current.code) || []).concat(current.errors)), new Map))
    .map(([key, value]) => ({code: key, errors: value}));
console.log(result);

If you prefer the errors to be a single string, add the .join() method:

.map(([key, value]) => ({code: key, errors: value.join()}));

Legacy Version

var codes = ["12345", "12345", "67890", "67890", "67890", "67890", "12092", "12092"];
var errors = ["12345 error 1", "12345 error 2", "67890 error 1", "67890 error 2", "67890 error 3", "67890 error 4", "12092 error 1", "12092 error 2"];

var grouped =
  codes.map(function(code, index) {
    return {
      code: code,
      errors: errors[index]
    };
  })
  .reduce(function(accumulator, current) {
    accumulator[current.code] = (accumulator[current.code] || []).concat(current.errors);
    return accumulator;
  }, {});

var result = Object.keys(grouped).map(function(code) {
  return {
    code: code,
    errors: grouped[code]
  }
});

console.log(result);

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

Utilizing a setTimeout function within a nested function in JavaScript

Recently delving into the world of JavaScript, I encountered an issue with a code snippet that goes like this: function job1() { var subText1 = ""; var subText2 = ""; var text = ""; var vocabulary = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijkl ...

Utilize React and Jest to handle errors by either mocking window values or resolving them

When my app attempts to inject environmental variables at runtime for docker using the window object, I encounter errors in my tests. The code snippet below shows the configuration: url config: declare const window: Window & typeof globalThis & ...

Utilize Javascript to pull information from a REST API and generate a dynamic table with the retrieved

Generating a table from JSON data obtained from a REST API without utilizing Angular poses a challenge in a specific application. My query is: Is it necessary to use var table = document.createElement("TABLE"); within the script to construct the entire ta ...

Preserving Foreign Key Relationships in Django Rest Framework Serializers

Within my project, I have two interconnected models named Task and Batch, linked through a Foreign Key field. My goal is to verify the existence of a Batch Object in the database before creating a new Task Object. The Batch object represents the current da ...

Is there a way to retrieve files from a main directory as well as all its subdirectories?

I'm looking to find a way to retrieve all JavaScript files located in the main directory and any subdirectories for my discord.js command handler. How can I make this happen? I have a functioning code snippet that successfully retrieves all .js files ...

What is the best way to reset an HTML file input using JavaScript?

Looking for a way to reset the file input in my form. I've tried setting the sources to the same method, but it doesn't delete the selected file path. Important: Trying to find a solution without having to reload the page, reset the form, or us ...

After sending the directories, an unusual issue arose that caught me off guard

Here is the code I have written:- const express = require("express"); const app = express(); app.get("/", function (req,res) { res.send("<h1>Hello World</h1>"); res.send(__dirname + '\\index. ...

Tips for retrieving the distance from the top of a specific div element and transferring it to another div

How can I add margin-top based on the tab that is clicked? Specifically, when TAB 4 is selected, I want the content to remain in the same position from the top. https://i.sstatic.net/ObDUg.jpg ...

What is the proper way to implement array mapping within methods in Vue.js?

Is there a way for me to match my array id with my value id and then access the value.name? I have attempted it but couldn't get it right Below is the code I am working with: activity(val) { var act = this.items.map(function (val) { if ( ...

Incorporating images with JavaScript in Jade templates

Currently I have a layout.jade code that I am looking to modify the javascript for. My goal is to load an image onto the page every time it is reloaded using jade. Here is the existing code: html head title= title script(src='/libs/jquery/j ...

How does the "deliver_order" function retrieve the value of the name parameter?

function take_order(name, callback1) { console.log("order has been taken."); callback1(name); } function prosess_order(name, callback2) { console.log(`prosesing order for ${name}.`); callback2(name); } function deliver_order(name) { console.log ...

Tips for navigating through a webpage by scrolling

My goal is to automatically scroll down to the bottom of the page and then perform a specific action. With the help of uiautomator, I was able to retrieve the following information: index=2, resource-id=com.manoramaonline.arogyam:id/pager,class=android.sup ...

"Learn the steps to toggle a sub menu using an onclick event and how to hide it using another

I created a sidebar navigation that displays submenus on mouseover, but I want them to open on click and close when clicking on the same tab. Please take a look at my code on this CodePen link. Thank you. <nav class="navigation"> <ul class="mai ...

"Within the node.js framework, the search/query section of the URL appears

I am currently working on a website (client + server) that both operate from the same machine. Despite not encountering any issues in Chrome's developer tools, I am struggling to identify the source of a problem. My dilemma is with trying to POST a s ...

Can Javascript (PWA) be used to detect fake GPS or mock GPS in applications?

Looking for a solution to prevent users from using Fake Location tools in my PWA application that gathers absence location data. Is there a method or package in JavaScript to detect the presence of Fake GPS installed on the device? ...

transferring data from grails to javascript via a map

I am facing an issue with passing a Map object from my Grails controller to JavaScript. The code snippet in my controller is as follows: def scoreValue = new HashMap<String,String>(); scoreValue.put("0","poor"); scoreValue.put("1","good"); ... retu ...

Changing the background color of a PHP input based on the webpage being viewed - here's how!

I'm in the process of creating a website where each page will have its own unique background color. Additionally, I am using a PHP input for both the header and footer sections, which need to change their background colors based on the specific webpa ...

What's going on with the background color? It doesn't seem

I have incorporated Bootstrap into my html code and I am attempting to modify the background color of a div when the screen resolution changes from large to medium or small. Even though I have added a class, the change does not reflect when adjusting the ...

steps to iterate through an array or object in javascript

Hello, I am facing an issue while trying to loop through an array or object. Can someone help me out? Are arrays and objects different when it comes to using foreach? function fetchData() { fetch("https://covid-193.p.rapidapi.com/statistics", { ...

Navigate to the adjacent IDs

I have multiple sections with varying content and links (previous and next) to navigate to the next section. Initially, everything functions properly. However, when adding a new section in between existing ones, I am required to update all the ids to ensu ...