Iterating over an array and setting the key for a new array

I have encountered a challenge while attempting to create a new array where the key is the index of the original array.

var array = [
          {"tom": "red", "part":"green", "brow_id":45},
          {"tom": "red", "part":"yellow", "brow_id":1},
          {"tom": "red", "part":"yellow", "brow_id":2},
          {"tom": "maroon", "part":"cyan", "brow_id":45}
           ];
var newarray = {};

array.forEach(function(elem) {
        newarray[elem.brow_id] = elem;
                    });

The resulting array looks like this

         45: {"tom": "red", "part":"green", "brow_id":45},
         1:  {"tom": "red", "part":"yellow", "brow_id":1},
         2:  {"tom": "red", "part":"yellow", "brow_id":2},

However, I aim for it to include all the IDs from the original array in this format

        45: [{"tom": "red", "part":"green", "brow_id":45},{"tom": "maroon", "part":"yellow", "brow_id":45}]
         1:  {"tom": "red", "part":"yellow", "brow_id":1},
         2:  {"tom": "red", "part":"yellow", "brow_id":2},

What could be causing this issue?

Answer №1

One way to tackle this is by first checking if the property exists and assigning the element to it. If not, then check if it's an array and if it's not, create one. Then push the element into the array.

var array = [{ tom: "red", part: "green", brow_id: 45 }, { tom: "red", part: "yellow", brow_id: 1 }, { tom: "red", part: "yellow", brow_id: 2 }, { tom: "maroon", part: "cyan", brow_id: 45 }],
    object = {};

array.forEach(function(elem) {
      if (!object[elem.brow_id]) {
          object[elem.brow_id] = elem;
          return;
      }
      if (!Array.isArray(object[elem.brow_id])) {
          object[elem.brow_id] = [object[elem.brow_id]];
      }
      object[elem.brow_id].push(elem);
});

console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To achieve the desired output, you can utilize the reduce function for grouping and building.

var array = [{    "tom": "red",    "part": "green",    "brow_id": 45  },  {    "tom": "red",    "part": "yellow",    "brow_id": 1  },  {    "tom": "red",    "part": "yellow",    "brow_id": 2  },  {    "tom": "maroon",    "part": "cyan",    "brow_id": 45  }];

var result = array.reduce((a, elem) => {
  if (a[elem.brow_id]) {
    if (Array.isArray(a[elem.brow_id])) a[elem.brow_id].push(elem);
    else a[elem.brow_id] = [elem, a[elem.brow_id]];
  } else a[elem.brow_id] = elem; 
  
  return a;
}, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Another approach involves using forEach along with a correction to prevent duplicating elements in the new object.

var array = [{    "tom": "red",    "part": "green",    "brow_id": 45  },  {    "tom": "red",    "part": "yellow",    "brow_id": 1  },  {    "tom": "red",    "part": "yellow",    "brow_id": 2  },  {    "tom": "maroon",    "part": "cyan",    "brow_id": 45  }];

var newarray = {};

array.forEach(function(elem) {
  if (newarray[elem.brow_id]) {
    if (Array.isArray(newarray[elem.brow_id])) newarray[elem.brow_id].push(elem);
    else newarray[elem.brow_id] = [elem, newarray[elem.brow_id]];
  } else newarray[elem.brow_id] = elem;  
});

console.log(newarray);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

Utilizing Array.forEach() for grouping:

var items = [{"name":"apple","color":"red","id":1},{"name":"banana","color":"yellow","id":2},{"name":"kiwi","color":"green","id":3},{"name":"grape","color":"purple","id":1}];

var groupedItems = {};

items.forEach(function(item) {
  var key = item['id'];
  
  groupedItems[key] = key in groupedItems ? [].concat(groupedItems[key], item) : item;
});

console.log(groupedItems);

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

Rotating the camera around the origin in Three.js

Hey, I'm having some trouble with what I thought would be a simple task. I have a group of objects at the origin, and I'm trying to rotate a camera around them while always facing the origin. According to the documentation, this code should work: ...

Is it possible to selectively export certain interfaces within a .d.ts file?

// configuration.d.ts export interface Configuration { MENU_STRUCTURE: Node[]; } interface Node { name: string; } Looking at the snippet above, I am aiming to only export Configuration. However, I noticed that I can also import Node from an ext ...

JSON is throwing an error because a semi-colon is missing before a statement

I encountered a perplexing error despite receiving the correct response and being able to view the JSON content: Below is the request: $.ajax({ type: "GET", url: urlTwitter, contentType: "applic ...

Inject the code snippet from CodePen into a WordPress webpage

I have a WordPress page where I want to integrate the HTML, CSS and JS code from my Codepen project. The styling appears to be working correctly, but the JavaScript is not functioning as expected. You can view the page here: Could someone assist me in pr ...

Struggling to set up the connection between React-Redux connect and the Provider store

Currently utilizing Redux with React Native for state management. I've set up the store and Provider successfully it seems, as I can utilize store.getState() and store.dispatch(action()) from any component without issue. However, I'm encountering ...

What is the best way to transmit two variables in a single message with Socket.io?

My goal is to send both the clientid and username through the socket communication. client.userid = userid; client.username = username; client.emit('onconnected', { id: client.userid, name: client.username }); I attempted this approach, how ...

Step by step guide on including a JavaScript function in a web worker using importScripts

I am encountering an issue with my worker.js file: self.importScripts('/static/utils/utils.js') onmessage = (e) => { let a = e.data[0] let b = e.data[1] let c = func1(a,b) postMessage(c) } The structure of the utils.js file ...

Maintaining datatype integrity in MongoDB Stitch when decrementing with update statements

Using a MongoDB Stitch function, I have two collections: communities and posts. Whenever a new document is inserted in the post collection, I need to increment the summary.postCount in the communities collection by +1. Similarly, when the status of a post ...

During the click event, two distinct $.ajax requests interfere and cancel each other out

Here's a dilemma I'm facing: On my webpage, I have implemented two different click events. The first one opens a modal displaying a larger image when you click on a thumbnail picture (similar to Instagram on PC - I created an Instagram clone for ...

Using a JavaScript class rather than an ID for toggling visibility

As a complete newbie to JavaScript, I've come across similar questions but I'm lost when it comes to coding - help needed! So here's the code I have so far, and I'm hoping someone can assist me. Currently, I have JavaScript set up to s ...

An expression must be a modifiable lvalue in order to set an element within a dynamic array consisting of fixed-length arrays

Within my C++ program, I am working with a dynamic char array where each element is a fixed-size array with a length of MAX_LINE_SIZE. This is how I have set up the array inside my main function: char (*text)[MAX_LINE_SIZE] = nullptr; The goal is for thi ...

"Unexpected compatibility issues arise when using TypeScript with React, causing errors in props functionality

Just the other day, my TypeScript+React project was running smoothly. But now, without making any changes to the configurations, everything seems to be broken. Even rolling back to previous versions using Git or reinstalling packages with NPM does not solv ...

Tips for making an appended element match the height of an image

After embedding the div .soonOverlay into specific .smallCatalogBlock's, I am facing difficulty in adjusting the height of soonOverlay to match only the height of the img within smallCatalogBlock. Currently, its height extends throughout the entire co ...

Is it possible to replicate this JavaScript syntax in C++?

As someone who frequently writes JavaScript, I find myself particularly drawn to the syntax of this feature. While I'm uncertain about its nomenclature, here's an illustrative example: object.function1().function2().function3() I understand tha ...

MongoDBError: Unauthorized access attempt for [action] operation by the user is prohibited

I've been struggling with this error for quite some time now, attempting all the recommendations on this forum without success. My goal is to develop a website where users can register and their credentials are saved in a database. Below is a snippet ...

Having difficulty in successfully transmitting a dictionary via AJAX (POST) to Python (Django views) resulting in an empty dictionary every time

When I include this script in the head of the HTML : <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> and then use a button to call a function: <div> ...

Incorporating numerous dropdown menus to a table filled with data retrieved from a database

I have implemented a dynamic table that adds a new row at the end when a button is clicked. One of the columns in the table contains a dropdown list, and I want this dropdown list to display values from a database. This is how I am constructing my table ...

Error: TypeScript encountered an issue while attempting to access a property that is undefined

I just can't seem to figure out what's missing here. Running the following code gives me this error: Uncaught TypeError: Cannot read property 'addEventListener' of undefined" class Editor{ public co ...

Troubleshooting problem with chat messages due to Firestore snapshot limit or limitToLast issues

I'm currently developing a chat application using React Native with Firestore integration. To retrieve the latest 25 messages in the Chat screen, I am ordering them by timeSent and limiting to last 25 items: firestore .collection('group') ...

Assistance is required for establishing a connection between php and js. The process begins with executing a sql query to extract the necessary data, which is then encoded into JSON format

I have encountered an issue with a project I am working on solo, involving a sidecart in a PHP file with external links to SQL, CSS, and JS. The problem arose when attempting to insert necessary data into JS using JSON encoding. <?php session_start(); ...