Combining two objects by id and grouping identical key-value pairs together

      var routePlan = [
      {
        "id" : 1,
        "farmerName" : "Farmer1",
        "farmerId" : 1
      },
      {
        "id" : 2,
        "farmerName" : "Farmer2",
        "farmerId" : 2
      },
      {
        "id" : 1,
        "farmerName" : "Farmer3",
        "farmerId" : 3
      }
    ];

I'm looking to consolidate objects with the same id into a single combined object using either javascript or angularjs.

      var routePlan = [
      {
        "id" : 1,
        "farmers" : [
          {
            "farmerName" : "Farmer1",
            "farmerId" : 1
          },
          {
            "farmerName" : "Farmer3",
            "farmerId" : 3
          }
        ]
      },
      {
        "id" : 2,
        "farmerName" : "Farmer3",
        "farmerId" : 2
      }
    ];

I've searched online for examples, but haven't found one that fits my specific needs. Any help would be appreciated!

Answer №1

There is definitely room for improvement, but here is a functional solution:

let temporary = routePlan.reduce(function(accumulator, item){
    accumulator[item.id] = accumulator[item.id] || [];
    accumulator[item.id].push({ "farmerName": item.farmerName, "farmerId" : item.farmerId });
    return accumulator;
}, {});

let updatedRoute = Object.keys(temporary).map(function(key){ 
    let newObject = {}

    if (temporary[key].length > 1){
        newObject.id = parseInt(key);
        newObject.farmers = temporary[key];
    }
    else
    {
        newObject = Object.assign({}, routePlan.find(element => element.id == key));
    }

    return newObject;
});

Take note of the reduce function being used to group your objects by id.

Answer №2

If you want to organize data into groups, consider using a hash table for reference.

var info = [{ id: 1, farmerName: "Farmer1", farmerId: 1 }, { id: 2, farmerName: "Farmer2", farmerId: 2 }, { id: 1, farmerName: "Farmer3", farmerId: 3 }],
    hashTable = Object.create(null),
    groupedData = info.reduce(function (result, item) {
        function getData(obj) {
            return ['farmerName', 'farmerId'].reduce(function (res, key) {
                res[key] = obj[key];
                return res;
            }, {});
        }
        if (!(item.id in hashTable)) {
            hashTable[item.id] = result.push(item) - 1;
            return result;
        }
        if (!result[hashTable[item.id]].farmers) {
            result[hashTable[item.id]] = { id: item.id, farmers: [getData(result[hashTable[item.id]])] };
        }
        result[hashTable[item.id]].farmers.push(getData(item));
        return result
    }, []);

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

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

Could you share the most effective method for implementing a live search feature using javascript or jquery?

While attempting to create a live search for a dataset containing over 10,000 rows, I specified the DOM structure that is available. Despite my efforts to check each result after a single input during the live search process, my browser keeps hanging. Is t ...

Tips for adding JSON values to an object

There is a specific object called SampleObject which has the following structure: { ID: "", Name: "", URL: "", prevName: "", Code: "", } I am looking to insert the values from the JSON object below (values only): var object = { "Sample ...

What is the recommended way to configure the build.gradle file for the app build process?

I am currently working on building the app using the command provided below. /android gradlew assembleRelease My main query at this point is whether it is necessary to eliminate the debug of signingConfigs and debug of buildTypes when transitioning into r ...

A label in nativescript not displaying a two-digit number

I've encountered a peculiar issue with my user interface. I have a barcode scanner on my phone that scans barcodes and stores them in an observable array (which is functioning correctly). I also have a label that displays the length of the array. When ...

The NetSuite https.post() method is throwing an error that reads "Encountered unexpected character while parsing value: S. Path '', line 0, position 0"

I'm currently facing an issue when trying to send the JSON data request below to a 3rd party system using the "N/https" modules https.post() method. Upon sending the request, I receive a Response Code of "200" along with the Error Message "Unexpected ...

Implementing the React Router into a ReactJS project: Methods to prevent users from clicking on links within React-Router's <Link> component

I'm exploring React-Router's Link and have set up the following: <Link to={...}>{this.props.live? "Live": "Not Live"}</Link> In this configuration, if this.props.live is present, I want to display the text "Live" which will lead to ...

Tips for showcasing an array in nested elements within an Angular mat-tree

I'm new to Angular and I need help displaying an array's values within the child elements of a material tree. Specifically, I want to show the names of fruits (such as Apple, Banana...) in the child elements. The colors and discounts from the ar ...

Having difficulty accessing the ::after element on Firefox when attempting to click

I've encountered an issue with my HTML and CSS code - it functions perfectly on Chrome, yet behaves differently on Firefox. button#groupToggle { background: 0 0; border: 1px solid #e6e6ed; color: #222; float: none; margin: 0 0 ...

Can I deactivate JavaScript on my website directly from my server settings?

I'm currently attempting to link my Android application to a PHP script hosted on a free server. However, when my app tries to access the page, I receive an HTML message stating that JavaScript is disabled and needs to be enabled in order to view the ...

Tips for displaying personalized error messages from your REST API in a JavaScript client

I'm utilizing a Java REST API that has been generated using swagger. If the client is unauthorized, I am sending custom error messages in response. public Response collaborationCollabIdDelete(Integer collabId, SecurityContext securityContext, Str ...

"Turn a blind eye to Restangular's setRequestInterceptor just this

When setting up my application, I utilize Restangular.setRequestInterceptor() to trigger a function that displays a loading screen whenever a request is made with Restangular. Yet, there is a specific section in my application where I do not want this fun ...

Using knex.js to pipe data to an express server

I'm encountering an issue with knex.js and express. Here is the code snippet in question: userRouter.get('/:userId', function (req, res) { DB('users').where({ id: req.params.userId }).first('name').pipe(res); }); ...

Build a nested block containing a div, link, and image using jQuery or vanilla JavaScript

I have a button that, when clicked, generates a panel with 4 divs, multiple href links, and multiple images. I am new to web programming and understand that this functionality needs to be in the Javascript section, especially since it involves using jsPlum ...

How can I dynamically retrieve the width of an image in React as the screen size changes?

I have successfully implemented an image hover effect on my website. When I hover over a certain text, an image appears. The image is responsive, but I am facing an issue where I want the width of the text to be equal to the width of the image. When I resi ...

What is the best way to insert a permanent script tag into the body of a Gatsby site? Can conditional rendering be used to control

As an illustration: - const nation = "USA" import chat from './utils/script'; // script is imported from a file if(nation === "USA") // utilized conditionally in the component { chat } else { console.log("Not USA") } inform me witho ...

Automatically launching a new tab upon page load in a React application

I have a specific requirement that when a form is loaded, a new browser tab should automatically open with a URL based on one of the attributes. After researching some solutions on various platforms like Stack Overflow, I came across this helpful thread: M ...

What is the method for retrieving the XMLHttpRequest errors registered with addEventListener?

I am struggling to find a solution. https://i.stack.imgur.com/bRJho.gif ...

Tips on placing an li element into a designated DIV

Just starting out with jquery and working on a slider project. Here's what I have so far: <ul> <li> <img src="image.jpg"><p>description of the current image</p></li> <li> <img src="image.jpg"> ...

The absence of the function crypto.createPrivateKey is causing issues in a next.js application

For my next.js application, I am utilizing the createPrivateKey function from the crypto module in node.js. However, I encountered an issue as discussed in this thread: TypeError: crypto.createPrivateKey is not a function. It seems that this function was a ...

Struggling to make image uploading function with Flask and JQuery

Utilize the code snippet below to submit forms and retrieve a modified version of text from Flask using AJAX and JQuery: from flask import Flask, render_template, request, jsonify app = Flask(__name__) @app.route('/') def index(): return re ...