Ways to prevent the repetition of keys associated with values

I am currently dealing with an array called serialNumbers, which can have different structures. For example:

lot: 1  Serial: 2
lot: 1  Serial: 3
lot: 1  Serial: 4

...or it could look like this:

lot: 1  Serial: 5
lot: 1  Serial: 9
lot: 8  Serial: 2
lot: 8  Serial: 4

In my attempt to manipulate the data, I created a dictionary named dictSerials using the following code:

var dictSerials = []
if (serialNumbers.length > 0) 
    for (var i of serialNumbers) {
        dictSerials.push({
            key: i.value.lot,
            value: i.value.serial
        })
    }

However, my desired outcome is to have an object structured like this:

Key: 1  Value: 2, 3, 4, 5, 9
Key: 8  Value: 2, 4

If anyone has insights on how to achieve this, your assistance would be greatly appreciated. Thank you!

Answer №1

One way to meet your requirement is by utilizing the reduce function to group keys and values together.

let data = [{type: 'A', number: 1},{type: 'A', number: 2},{type: 'B', number: 3},{type: 'B', number: 4},{type: 'C',number: 5},{type: 'D',number: 6}],
    outcome = Object.values(data.reduce((accumulator, current) => {
      (accumulator[current.type] || (accumulator[current.type] = {Key: current.type, Value: []})).Value.push(current.number);
      return accumulator;
    }, {}));
    
console.log(outcome);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

If you're looking for a more efficient approach, consider this solution:

 let data = [
      {
        name: "foo1",
        value: "val1"
      }, 
      {
        name: "foo1",
        value: ["val2", "val3"]
      },
      {
        name: "foo2",
        value: "val4"
      }
    ];

    let result = [];

    data.forEach(item => {
      let existingItem = result.find(obj => obj.name === item.name);
      if (existingItem) {
        let index = result.indexOf(existingItem);
        result[index].value = result[index].value.concat(item.value);
      } else {
        if (typeof item.value === 'string') {
          item.value = [item.value];
        }
        result.push(item);
      }
    });

    console.dir(result);

Answer №3

Here is a straightforward method using dual forEach loops:

const data = [
  {lot : 1, Serial : 2},
  {lot : 1, Serial : 3},
  {lot : 1, Serial : 4},
  {lot : 1, Serial : 5},  
  {lot : 1, Serial : 9},
  {lot : 8, Serial : 2},
  {lot : 8, Serial : 4}
]

let groupedData = [],
  resultData = [];

data.forEach((entry) => {
  (resultData[entry.lot] || (resultData[entry.lot] = [])).push(entry.Serial)
})

resultData.forEach((entry, index) => {
  groupedData.push({
    "key": index,
    "value": entry.join(',')
  })
});

console.log(groupedData)

Answer №4

One effective way to achieve this is by utilizing a Map.

var productCodes = [
  {item:{product:1, code: 2}},
  {item:{product:1, code: 3}},
  {item:{product:1, code: 4}},
  {item:{product:1, code: 5}},
  {item:{product:1, code: 9}},
  {item:{product:8, code: 2}},
  {item:{product:8, code: 4}},
 ];

var codeMapping = new Map();
if (productCodes.length > 0) {
  for (var item of productCodes) {
      if(!codeMapping.has(item.item.product)) {
        codeMapping.set(item.item.product, [item.item.code]);        
      } else {
        var values = codeMapping.get(item.item.product);
        values.push(item.item.code);
        codeMapping.set(item.item.product, values);        
      }      
  }
}
//Final Result
for (var [key, value] of codeMapping.entries()) {
  console.log("Product: " + key + " Code: " + value.join(","));
}

Answer №5

function createSerialDictionary(serialNumbers) {

    var serialDict = {};

    if (serialNumbers.length > 0) {
        for (let num of serialNumbers) {
            let lotNumber = num.lot;
            let serialNumber = num.serial;

            if (!serialDict[lotNumber]) { 
                serialDict[lotNumber] = [];
            }

            serialDict[lotNumber].push(serialNumber); 
        }
    }

    return serialDict;
}

let items = [
    {lot : 1, serial : 2},
    {lot : 1, serial : 3},
    {lot : 1, serial : 4},
    {lot : 1, serial : 5},
    {lot : 1, serial : 9},
    {lot : 8, serial : 2},
    {lot : 8, serial : 4}
];

let finalObject =  {
    serializedItems: createSerialDictionary(items)
}

JSON.stringify(finalObject); // {"serializedItems":{"1":[2,3,4,5,9],"8":[2,4]}}

Answer №6

var dictSerials = []
if (serialNumbers.length > 0) {
    for (var i of serialNumbers) {

      if(!dictSerials[i.value.lot]){
          dictSerials[i.value.lot] = [];
      }

       dictSerials[i.value.lot][] = i.value.serial;
    }
}

This particular code snippet is designed to assign values to their respective keys in the dictionary.

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

Unusual host value being returned by next/headers in Next.js version 13

In my current Next.js project, I am utilizing next/headers to dynamically set a baseUrl for calls to my API. const baseUrl = () => { const protocol = process?.env.NODE_ENV === "development" ? "http" : "https"; const ...

Determine the sequence of a div based on its class

Here is the code snippet I am working with: <div class="test"></div> <div class="test"></div> <div class="test"></div> <input type="button" class="button" value="get number"> <div class="test"></div> & ...

Is there a method to create a typecheck for hasOwnProperty?

Given a certain interface interface Bar { bar?: string } Is there a way to make the hasOwnProperty method check the property against the defined interface? const b: Bar = { bar: 'b' } b.hasOwnProperty('bar') // works as expected b. ...

Issue with adding json_encode to the end

I am trying to add the service using jQuery.each(), but it is not working in my JavaScript code? This is the output I am getting from my PHP code: { "data": [{ "service": ["shalo", "jikh", "gjhd", "saed", "saff", "fcds"], "address": " ...

The information is not appearing in the dropdown menu

The select tag for chapters is not displaying the result from the query properly. Instead of showing in the select tag, the chapter names are being displayed as echo statements. <!doctype html> <html> <head> <meta charset="utf-8"> ...

Incorporate the ability to display a shape on a map when hovering over a table element, without the need to manually code a JavaScript function for every instance

I came across a script online that allows me to hover over text and have a shape appear on an imagemap. It's functional, but only works for a single instance. Is there a way to implement a JavaScript that handles individual instances so I don't h ...

Determining the file size of an HTML and JavaScript webpage using JavaScript

Is there a way to determine the amount of bytes downloaded by the browser on an HTML+JS+CSS page with a set size during page load? I am looking for this information in order to display a meaningful progress bar to the user, where the progress advances bas ...

Store a new JSON item in the localStorage

Currently, I am tackling a task in Angular where the objective is to store items to be purchased in localStorage before adding them to the cart. There are four distinct objects that users can add, and an item can be added multiple times. The rule is to ch ...

Dealing with the Back Button Problem in History API and History.js

Using Ajax to load the page presents a challenge when the user clicks the back button. Here is the scenario: Initial page (index.php) is loaded User clicks on a link The new page loads successfully via Ajax User clicks the back button The initial page is ...

Access the data within a jsonArray using Cypress

I'm dealing with a test.json file that contains a jsonArray [{ "EMAIL": "email_1", "FIRST_NAME": "Daniel" }, [{ "EMAIL": "email_2", "FIRST_NAME": "John" }] ] I'm trying to figure out how to use cypre ...

Struggling to delete items from an array in react.js

I am attempting to remove an item from a nested childArray within another Array. This is my current approach: const childArrayHandler = (childData, sub, questionId, data, btnId) => { // Manage color change on click const isInList = selectedBtnL ...

Having trouble with Vue 3 Composition API's Provide/Inject feature in Single File Components?

I am currently developing a VueJS 3 library using the Composition API. I have implemented Provide/Inject as outlined in the documentation. However, I am encountering an issue where the property in the child component remains undefined, leading to the follo ...

retrieving data from GET variables and sending to a PHP array

Is there a way to retrieve form variables and store them in an array in memory without reloading the page? I'm not very experienced with this, so any guidance would be appreciated. My goal is to update a JSON file using PHP based on form inputs. JSON ...

The concept of nested ng-repeat in AngularJS

My HTML structure is as follows: <div class="fields-plan"data-ng-repeat="roomname in assign.roomname"> <section> <span>Room: {{roomname}}</span> </section> <ul data-ng-repeat="r ...

Updating SVG colors using VueJS

I'm struggling to change the color of an existing static SVG image. Here's the code I have: <img class="icon-shop" src="@/assets/icon-shop.svg"/> <style> .icon-shop { width: 32px; fill: orange; stroke: oran ...

Guide to retrieving a string value rather than Json output with a mongodb aggregate function

I have a function that retrieves the value of the 'minHospitalization' field from the database. The response from this function is '[{"minHospitalization":1}]' Instead of returning the value in JSON format, I want to return just ' ...

Creating a canvas texture on tube geometry with three.js for optimal display on iPad devices

I have a 3D model of a tube geometry with 18000 coordinates on the production side. To simplify, I am selecting every 9th coordinate to plot 9000 coordinates for building the tube geometry using only the CanvasRenderer. When utilizing vertexColors: THREE. ...

Adding an operation to a function that is linked to an event

On one of my pages, I have a button that triggers some ajax calls with data binding. The binding code is generic and used in various parts of the application, so altering its behavior could impact other users. However, I now have a specific requirement fo ...

I'm receiving a TypeError in Nodejs indicating that the hashPassword function is not recognized as a function. Can anyone offer advice on how to

How's everything going? I could really use your assistance! I'm currently working on developing an API for registering authenticated users, with data storage in the MongoDB Atlas database (cloud). Unfortunately, I've run into a troubling er ...

Is it possible to automatically submit a form at regular intervals without reloading the page and simultaneously insert the submitted data into

I am attempting to automatically submit a form every x number of seconds without refreshing the page and then insert the input data into a MYSQL database. The problem I'm facing is that while I can successfully insert the form's input value into ...