Tips for iterating through an array of object literals and combining values with matching IDs

Looking for a more efficient way to iterate through an array of object literals and combine values in objects with duplicate IDs.

Is there a smarter approach than utilizing multiple nested for loops?

Here is the sample data provided:

{ "theList": [
    {
        "id": 101,
        "name": "Bubbles' Cat Farm",
        "number": "123"
    },
    {
        "id": 102,
        "name": "Sunnyvale Park",
        "number": "456"
    },
    {
        "id": 101,
        "name": "Bubbles' Cat Farm",
        "number": "789"
]};

The expected output should be:

{ "theList": [
    {
        "id": 101,
        "name": "Bubbles' Cat Farm",
        "number": "123, 789"
    }, 
    {
        "id": 102,
        "name": "Sunnyvale Park",
        "number": "456"
]}


Answer №1

To consolidate and manipulate data in JavaScript arrays, you can utilize the reduce method.

let items = [{ "id": 101,"name": "Bubbles' Cat Farm","number": "123"},{"id": 102,"name": "Sunnyvale Park","number": "456"},{"id": 101,"name": "Bubbles' Cat Farm","number": "789"}];

let output = items.reduce((result, item) => {
  if(result[item.id]){
    result[item.id].number += ', ' + item.number;
  } else {
    result[item.id] = item
  }
  return result
},{});

console.log(Object.values(output))

Answer №2

By utilizing the reduce method in conjunction with the findIndex function, you can accomplish your desired outcome.

const items = [{
    "id": 101,
    "name": "Bubble's Cat Farm",
    "number": "123"
  },
  {
    "id": 102,
    "name": "Sunnyvale Park",
    "number": "456"
  },
  {
    "id": 101,
    "name": "Bubble's Cat Farm",
    "number": "789"
  }
]

const updatedItems = items.reduce((accumulator, currentValue) => {
  const index = accumulator.findIndex(item => item.id === currentValue.id);
  if (index === -1) {
    accumulator.push(currentValue);
  } else {
    accumulator[index].number += ", " + currentValue.number;
  }
  return accumulator;
}, [])

console.log(updatedItems)

Answer №3

In the case where number is the sole key with unique values, you can achieve the desired outcome by utilizing the reduce function:

const data = {"items":[{"id":101,"name":"Bubbles' Cat Farm","number":"123"},{"id":102,"name":"Sunnyvale Park","number":"456"},{"id":101,"name":"Bubbles' Cat Farm","number":"789"}]}

const result = data.items.reduce((acc, {id,name,number}) =>{
  acc[id] 
    ? acc[id]["number"] += ", " + number 
    : acc[id] = {id,name,number};
    
  return acc
},{})

const finalResult = { "items": Object.values(result) }
console.log(finalResult)

Build an accumulator object with each unique id as a key and the required object for the final array as its value. Concatenate the number values if an id already exists in the accumulator, otherwise, add a new key to the accumulator.

{
  "101": {
    "id": 101,
    "name": "Bubbles' Cat Farm",
    "number": "123, 789"
  }
}

Finally, utilize Object.values to extract only the values of the items property into an array.

Answer №4

One approach is to transform your container into a dictionary, using the ID as the key and an empty list as the value. As you iterate through the data, check if the key exists. If it doesn't, create a new list with that item. If the key already exists, simply add the value to the existing list.

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

JavaScript layout: Thymealf

I have a unique thymeleaf template like so: <body> <div id="layout"> <!-- Menu toggle --> <a href="#menu" id="menuLink" class="menu-link"> <!-- Hamburger icon --> <span>& ...

Ways to effectively pair a radio button with a dropdown menu

function radioCheck() { document.getElementById("last").checked = "checked"; } <label> <input type="radio" name="Ppub" value="" checked="checked">All Dates </label> <br> <label> <input type="radio" id="last" name="Ppu ...

Another project cannot import the library that was constructed

I am in the process of creating a library that acts as a wrapper for a soap API. The layout of the library is structured like this: |-node_modules | |-src | |-soapWrapperLibrary.ts | |-soapLibraryClient.ts | |-types | |-soapResponseType.d.ts The libra ...

When choosing the child option, it starts acting abnormally if the parent option is already selected in Angular

I am encountering an issue while trying to select the parent and its children in the select option. The concept is to have one select option for the parent and another for the child. I have parent objects and nested objects as children, which are subCatego ...

Establish a JSONB index in Postgres for a sub-object within an array

My table myTable includes a JSONB column called myJsonb with a specific data structure that I wish to index, shown below: { "myArray": [ { "subItem": { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemai ...

Effortlessly glide to a specific div ID upon page load using the URL address

One way to implement smooth scrolling to an anchor on page load is by using jQuery. Here's an example code snippet: $(function(){ $('html, body').animate({ scrollTop: $( $('#anchor1').attr('href') ).offset(). ...

Instructions on passing a PHP variable as a parameter to a JavaScript function when a button is clicked

In my implementation of codeigniter 3, I have a view page where the data from $row->poll_question is fetched from the database. The different values within this variable are displayed on the voting.php page. Next to this display, there is a button label ...

The bundle.js file is displaying HTML code instead of JavaScript

I have been working on setting up redux server-side rendering using express.js. Most of the setup is done, but I encountered an error while trying to render the page in the browser. The error message Uncaught SyntaxError: Unexpected token < is appearin ...

Navigating fluently in React Native applications

Struggling to grasp the proper implementation of navigation in RN? The provided code snippet should shed light on the current scenario. HeaderConnected is equipped with a menu button component that utilizes a custom navigate prop for opening the Drawer me ...

ng-model assigns the value to the select

Below is the angularjs directive I have created: dicApp.directive('listpanel', function ($resource) { return { restrict: 'E', template: '<select ng-model="selectedDictionary" ng-change="listChange()">&apo ...

While developing my project in NextJS, I encountered a frustrating issue where the build process would fail consistently, even though the development environment ran smoothly. The

Hello everyone, I'm a beginner posting here for the first time. I am still getting the hang of React and JavaScript in general, and currently working on a project in NextJS. It's interesting to note that my project runs smoothly when I use next d ...

When the properties change, React Router Redux does not get rendered

I am encountering a challenge with using react router redux, where everything seems to be working well except for rendering when props change. Index.js import React from 'react'; import ReactDOM from 'react-dom'; import {Provider} fro ...

Exploring the Information Within HTML Forms

When my HTML form sends data to the server, it looks like this: { r1: [ '1', '2', '3' ], r2: [ 'Top', 'Greg', 'Andy' ], r3: [ 'validuser', 'invaliduser', 'validuser&a ...

Is it unorthodox to utilize constructor instances as prototypes in "WebGL - Up and Running"?

In the book "WebGL - Up and Running," a unique custom geometry is created in a rather straightforward manner. However, what caught my attention was the penultimate line of code. Here's how it looked: Saturn.Rings = function ( innerRadius, outerRadius ...

Ways to Insert Text and Values into an Array

{{ "user": "randomuser", "message": "require assistance" }, { "user": "automated assistant", "message": "do you need any help?" }, { "user": "randomuser", "message": "another inquiry" } I am seeking to extract additional paragraphs ...

"Header background image gradually fades out and disappears as you scroll, revealing a bottom gradient effect in a React application

When I scroll, my header image fades away. I used JavaScript in my React app to achieve this effect: useEffect(() => { const handleScroll = () => { if (parallaxDiv.current) { parallaxDiv.current.style.backgroundPositionY = `${ ...

Confirm that the form is valid prior to displaying the Bootstrap modal popup

My PHP file contains a simple form and a Bootstrap modal. When the submit button is clicked, the Bootstrap modal will be displayed. The form includes: https://i.sstatic.net/10R2r.png I want to validate the fields in the form. If successful, I then need ...

Having trouble with the response function not functioning properly within an AJAX autocomplete

I have implemented an autocomplete feature using the jQuery UI plugin from http://jqueryui.com/autocomplete/#remote-jsonp. $("#city" ).autocomplete({ source: function( request, response ) { $.ajax({ url: 'index.php?secController= ...

What steps can be taken to empower users to make changes to pre-selected data within the vue-select component?

Usage of vue-select component: Currently, I am looking for a way to enable my users to edit data that has already been selected. After going through the documentation, I couldn't find a direct method to achieve this. If anyone has experience working ...

Tips for enhancing the width of the extrude shape in the x and z axes using Three.js

After creating a shape using extrude geometry, I found that I needed to increase the thickness along the x and z axes. Although I used bevelThickness to increase the thickness along the y axis, I still need to adjust it further. For reference, please see ...