Steps to transform identical or duplicate "identifiers" containing distinct values within a construct into a structured array

I am facing a challenge with objects that have similar ids.

[{
"_id": "603",
"name": 'innova',
"type": 'suv',
"brand": 'toyota'
},
{
"_id": "902",
"name": 'i20',
"type": 'hashback',
"brand": 'hyundai'
},
{
"_id": "603",
"name": 'indigo',
"type": 'haskback',
"brand": 'toyota'
}]

In order to address this, the data should be converted to:

[{
"_id": "603",
"name": ['innova', 'indigo'],
"type": ['suv', 'haskback'],
"brand": ['toyota', 'toyota']
}, {
"_id": "902",
"name": ['i20'],
"type": ['hashback'],
"brand": ['hyundai']
}]

Despite attempting to use Object.keys and Object.Values by pushing them if the id already exists, I was unsuccessful in resolving the issue.

Answer №1

Utilize the reduce method to construct an object based on the `_id` key. Then, utilize Object.values() to retrieve the desired object.

const data = [{
    "_id": "603",
    "name": 'innova',
    "type": 'suv',
    "brand": 'toyota'
  },
  {
    "_id": "902",
    "name": 'i20',
    "type": 'hashback',
    "brand": 'hyundai'
  },
  {
    "_id": "603",
    "name": 'indigo',
    "type": 'haskback',
    "brand": 'toyota'
  }
]

const newData = data.reduce((acc, row) => {

      if (!acc.hasOwnProperty(row._id)) {
          acc[row._id] = {
            "_id": row._id,
            name: [row.name],
            type: [row.type],
            brand: [row.brand]
          };
        } else {
          acc[row._id].name.push(row.name);
          acc[row._id].type.push(row.type);
          acc[row._id].brand.push(row.brand);
        }

        return acc;
      }, {}); 
      
      console.log(Object.values(newData));

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

A guide to resolving the error "Cannot read properties of undefined (reading 'length')" while implementing pagination with react, Material-UI, and TypeScript

As I work on my code, my goal is to display a limited number of cards per page based on the data stored in a JSON file. I anticipated that clicking on the ">" or "<" icon would navigate to the next or previous page respectively, updating the displaye ...

In Vue2, you can utilize $ref to retrieve information from a child component and transfer it into the parent component's data

Trying to access child components' data in Vue2 and move it into the parent component's data without triggering an event. Saving count:20 from the child component into the parent component in the example below. Please let me know if there are any ...

Navigating with AngularJS

My server is utilizing angular for routing purposes. It sends a HTML file containing a js file with routing using angular js to the browser. Here is the server code (which sends the check.html with the routing file main.js) : var express = require("expre ...

Attempting to display my ejs template from a node server following the activation of a delete button, all without utilizing ajax

I have created a basic blog application using node.js for the backend and ejs for the frontend. Posting blogs using a web form works well by calling a post route. Now, I am facing an issue with implementing a delete button for each blog post. The current s ...

Does the rendering of HTML get blocked by CSS in the <head> section like it does with javascript?

While it's common practice to keep JavaScript at the bottom of the HTML document, does the same rule apply for CSS as well? I understand that we can't place external CSS files outside the HTML document. ...

pagination of data tables on the server side

I am looking to incorporate server-side pagination with data tables for my application. I have approximately 200 records and I now understand the concept of server-side pagination where we send individual AJAX requests for each page link. So, if I want to ...

How can Tweepy be utilized to extract the integer count and incorporate it?

Hope all is well with everyone here. My apologies if this question has been addressed previously, but I am currently working on the following task. cursor = tweepy.Cursor( api.search_tweets, q = '"Hello"', lang = 'en&ap ...

Error: Attempting to access the properties `line_items.amount`, `line_items.currency`, `line_items.name`, `line_items.description`, or `line_items` is not allowed

Hi there, I'm currently working on creating an Amazon-inspired platform and I've encountered an error while trying to integrate Stripe with the project. Can anyone provide some assistance? You can refer to the video tutorial I'm using by fol ...

Why does mapping only give me the last item when I try to map onto an object?

Why does mapping onto an object only give me the last item? Below is the object displayed in the console: 0: {Transport: 2} 1: {Implementation: 9} 2: {Management: 3} When I use ngFor, it only provides the last item const obj = this.assigned_group; // r ...

The Angular Syncfusion schedule is unable to call upon an object that may potentially be 'undefined'

Currently, I am developing an application using Angular Syncfusion to allow users to view and book appointments. I found a helpful resource at the following link: Below you can find the code snippet I have been working on: <ejs-schedule #scheduleObj ...

What is the best method for accessing data values from HTML within a JavaScript function?

Greetings, I am relatively new to using jquery and ajax. Here is a snippet of my code: .html <li class="list-group-item"> <h2>Vocabulary</h2> <h4> <span class="label label-success">Like Name</span& ...

ControlOrbiter - limit panning motion

Is there a way to restrict the camera's panning movement within a scene? I've experimented with adjusting the pan method in orbitControls, but I'm not completely satisfied with the outcome. I am hoping for a more convenient and proper solut ...

Fade transition not working on Vue image element

I have a Vue component that utilizes swiper.js for slide animations. The desired effect is for an image to transition from right to left, expanding from 300x300px to fill the screen, with content such as a title and description overlaying the text. Curren ...

Ways to showcase a numeric value retrieved from an API on my webpage?

Greetings, esteemed guest! You are visitor number <span id=VisitorCounter></span> <script> fetch("https://unique-api-source.com/visits/getvisitorcount", { method: "GET", // mode: "cors", headers: { ...

`Only firing event listener once`

I have created a JS module where I am adding a click event to all links that match a specific selector. Here is an example of how it's done: var Lightbox = (function () { var showLightbox = function () { // this does stuff }; var init = fu ...

Activating events with Jquery

Can anyone help me with this HTML and jQuery issue I'm facing? When I click on an image for the first time (when it has the class 'hide'), the first jQuery click function is executed. However, when I click on the image again, the second func ...

Retrieving data from the database without the need to reload the page

Hi there! I have a PHP script that fetches data from a database and I want to display this data within a div element with a "link" class without having to reload the page. Check out the code snippet below: <? include('config.php'); $rs = m ...

Unable to process form submission using Ajax in ASP.NET MVC

I'm having trouble with submitting a form using ajax and opening a modal dialog after the ajax function is successful. Whenever I click the submit button, the process doesn't complete. Where could the issue be, in the ajax method or somewhere el ...

During the bulk insert process, only a portion of the BinaryDocument(s) are successfully uploaded into the system

I've encountered a strange issue with document insertion. I am working with two types of documents - JSON and BinaryDocument - and performing bulk insert operations with a specific batch size limit. The problem arises when inserting BinaryDocuments. ...

Tips for receiving feedback when uploading multiple images

I've been facing challenges with receiving a response when uploading multiple images using the API. Despite getting a valid response when uploading a single image, I'm not getting the expected response for multiple uploads. Below is my code: fil ...