If the key for an object is already in existence, then append another object to

Currently, I am parsing through a considerable JSON file and handling key:value pairs within an object. The problem arises when I encounter a key that requires me to append another object to it, rather than simply overwriting it.

For instance:

var collection = {};

angular.forEach(items, function(item) {
  collection[item.Id] = item.data;
  //item.data is an object
});

Answer №1

After carefully considering the feedback I received from the initial post, I have reached a conclusion:

let myCollection = {};

angular.forEach(items, function(item) {
  if(myCollection[item.Id]){
    //If key exists, add to existing array
    myCollection[item.Id].push(item.info);
  }else{
    //If key doesn't exist, create a new array for the object
    myCollection[item.Id] = [item.info];
  }
});

Answer №2

A more contemporary approach: perhaps this will be useful to someone

let items = {};

items.forEach(item => {
  if(!items[item.id]){
    items[item.id] = [];
  }

  items[item.id] = [...items[item.id], item.details];
  // alternatively ------------------------------------
  // add item at the beginning
  // items[item.id] = [item.details, ...items[item.id]];
  // or --------------------------------------------
  // if you prefer not to change the reference every time 
  // items[item.id].push(item.details);
});

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

Adding the page number to the URL when paginating in AngularJS

I am currently developing an application that involves pagination through records by making API calls to the server like random/api/endpoint?page=1/2/3 As I paginate, I need to append the requested page number to the URL like http://www.paginate.com/some ...

Refreshing CSS-Element-Queries following an ajax request

I’ve been utilizing css-element-queries from the https://github.com/marcj/css-element-queries repository to tailor styles based on an element's dimensions. However, I encountered an issue when dynamically adding elements via ajax calls. The new elem ...

Components in array not displaying in React

I've been struggling to generate a table from an array in React. Typically, I retrieve data from a database, but for testing purposes, I manually created the array to ensure the data is correct. Despite following examples by enclosing my map code with ...

Having difficulty interpreting the responseText

Currently experimenting with Redis Webdis Dart Here's my code snippet #import('dart:html'); #import('dart:json'); class ChatClient { XMLHttpRequest listener; int parsePosition = 0; void connect(){ this.listener = ne ...

Extracting web search result URLs using Puppeteer

I'm currently facing an issue with the code I've written for web scraping Google. Despite passing in a specific request, it is not returning the list of links as expected. I am unsure about what might be causing this problem. Could someone kindly ...

Exploring the Towers of Hanoi Puzzle with Javascript

Recently, I've been working on a school project where I need to present an algorithm for solving the Towers of Hanoi puzzle. Utilizing my knowledge in HTML/CSS, I decided to visually represent the algorithm using JavaScript on a webpage. I've se ...

How can you enhance your HTML elements by incorporating classes and other features?

At this moment, the code I have is: var carDiv = $("<div/>").appendTo("#content"); var eUl = $("<ul/>").appendTo(carDiv); How can I transform it into <ul data-role="listview"> content </ul> Instead of <ul> ...

What are the steps to import a .obj 3D model into Three.js?

After incorporating your advice, here is the revised code: var renderer = new THREE.WebGLRenderer( { alpha: true } ); renderer.setSize( window.innerWidth, window.innerHeight ); element.appendChild( renderer.domElement ); var loader = new THREE.OBJLoader( ...

When incorporating "<" or ">" into a parameter value in Angular Translate and then showcasing it in a textarea with ng-model

In my Angular Translate string, I am using a parameter that can be in the form of <test>. However, when this translate is displayed in a textarea, it shows up as &lt;test&gt; instead of <test>. Is there a way to ensure it appears correc ...

Creating a loop to iterate through JSON data being received

I successfully used JSON to display data, but I am now wondering how I can print all the database entries into a div or table. JavaScript $(document).ready(function() { $.ajax({ type : 'POST', url : 'server.php', dataTyp ...

transferring iterative information via ajax data flow

My form includes hidden input fields that are manually declared in the AJAX data without a loop. How can I efficiently loop through them in the AJAX data? Below is my form script: <form method="POST" name="myform"> <?php for($i=1;$i<=5;$i+ ...

Determine the specific cell involved in an HTML5 drag-and-drop interaction within a table

I've been experimenting with the HTML5 drag and drop functionality in an Angular project. Here's the setup I'm working with: A container containing draggable 'objects' A table where users can drop the dragged elements Following ...

What is the process for accessing a user's followers and users they are following using the new Spotify Web API?

Having just checked out the latest Spotify API documentation, I'm curious about how to access information on a user's followers and following. Is there a way to retrieve this data using the new Spotify Web API? I am looking to make requests to t ...

Comparing v-show(true/false) and replaceWith: Exploring the best practice between Vue and jQuery

Currently, I am in the process of learning vue.js and have a question regarding the best approach to implement the following scenario: https://i.sstatic.net/2YBEF.png https://i.sstatic.net/YCEHG.png The main query is whether it is acceptable in HTML to w ...

The declaration file for the module 'tailwind-scrollbar' could not be located

Currently, I am in the process of utilizing Tailwind packages for a Next.js application, however, I have encountered an issue that has proved to be quite challenging to resolve. Every time I attempt to add a "require" statement to my tailwind.config.js fil ...

CSS Class Returns to Inactive State

One of my tasks involves adding a new class to an image. .bbbLink img { outline: 1px solid #ddd; border-top: 1px solid #fff; padding: 10px; background: #f0f0f0; } When hovering over the image, I apply the following styles, .bbbLink img ...

Enhance the functionality of the Bootstrap navbar by enabling the slideUp and slideDown effects

I can't get jQuery's slideUp and slideDown methods to smoothly animate the Bootstrap navbar. When I tried using the slideUp method, the navbar only slid up a little before disappearing completely, and the same issue occurred with the slideDown me ...

Express route fails to wait for Redis server response before moving on

How can I modify the code below to ensure that the res.json(...) command is not executed until all open calls to the Redis client.somecommand(..) have completed successfully? An issue occurs in the code where the client.hmset(uname, { ... } attempt to set ...

JavaScript error: forEach is not a function

I've encountered an issue while attempting to loop through a JSON object to extract data. Whenever I run my code, I receive this error: Type Error: element.listing.forEach is not a function. It's worth mentioning that I've used this method ...

Having trouble setting up discord.js on my device, getting an error message that says "Unable to install discord.js /

Trying to install Discord.JS by using the command npm install discord.js seems to be successful at first, but unfortunately it doesn't work as expected. Upon running the index.js file, an error message pops up indicating that the module discord.js is ...