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

Running a Node.js worker on an Amazon ECS-hosted server: A step-by-step guide

Our team is currently running a node server on Amazon ECS that receives up to 100 hits per second. Due to the single-threaded nature of JavaScript, we are hesitant to block the event loop. As a solution, we are looking to implement a worker that can peri ...

Loop through a JSON object to dynamically update the value of a specific key

I have a JSON object with keys and values, where some of the values are empty strings. I want to replace those empty values with the corresponding key name. However, when trying to get the value of a key within the loop, it returns undefined. JSON: "Forg ...

vuejs function for modifying an existing note

Method for editing an existing note with Vue.js in a web application This particular application enables users to perform the following tasks: Create a new note View a list of all created notes Edit an existing note Delete an existing note Prog ...

Ensuring a dependable detection of WebSocket connection status

I've been researching how to create a dependable method for recovering a WebSocket connection. After exploring various options, I discovered that one approach involves sending heartbeats (ping/pong) to the server and monitoring if the entire pong is ...

What is the mechanism behind declaring a function using square brackets in Node.js/Javascript?

Encountering something new while working with Node.js - a unique way of declaring functions. You can find an example at this link. 'use strict'; const Actions = { ONE: 'one', TWO: 'two', THREE: 'three' }; clas ...

What is preventing the bundling of my CSS into the application?

I'm facing an issue while setting up a new project using vue.js, scss, and webpack (with express.js on the server side and TypeScript). I copied over the configurations from a previous project where everything was working fine. According to my underst ...

Is there a way to implement a css/javascript property specifically for a div that is selected in the url?

Take for instance the scenario where I possess the URL example.com/#foo. In this case, CSS styling will be directed to the div with the id foo. If achieving this solely in CSS is not feasible, what methods in JavaScript or jQuery can be used efficiently ...

Tips for managing both DOM manipulation and state changes at the same time in AngularJS

<div my-custom-directive> <button id="myButton" ng-click="handleClick(mymodel.id)"><button> </div> app.controller('myCtrl', function($scope) { $scope.handleClick = function(id) { //Perform state change here without ...

Transforming table data into a JSON format

My goal is to generate a specific JSON format from a table. The table consists of rows and 4 columns. You can view my table here. I aim to create a JSONArray based on the table. The first value in the left column serves as the key in the JSON, while the la ...

Dividing the logic from the Express router while retaining the ability to utilize Express functionalities

As I embark on my journey of developing my first app using Node.js and Express, I have noticed that my router file is starting to get overcrowded with logic. It seems like there is too much going on in there. My solution to this issue is to pass a functio ...

Modify the website address and show the dynamic content using AJAX

$(function(){ $("a[rel='tab']").click(function(e){ //capture the URL of the link clicked pageurl = $(this).attr('href'); $("#Content").fadeOut(800); setTimeout(function(){ $.ajax({url:pageurl+'?rel=tab&apo ...

unable to retrieve element values using class names

I have created multiple h1 elements with the same class names listed below. <h1 class="h1">One</h1> <h1 class="h1">Two</h1> <h1 class="h1">Three</h1> <h1 class="h1">Four</h1> I have also added a button that ...

Crop multiple images using dropzone.js before uploading

Currently, I have integrated Bootstrap with dropzone.js to allow users to upload images via drag & drop. Everything is functioning smoothly, even with the ability to upload multiple images. However, my next goal is to implement image cropping before uplo ...

Verify the presence of the promotion code and redirect accordingly

I have created a special promotion page that I want to restrict access to only users who have received a unique code from me via email. To achieve this, I have designed the following form: <form accept-charset="UTF-8" action="promotion.php" method="po ...

html search table td

How can I perform a search in a specific column of a table? Here is the JavaScript script and input tag that I am using: <script type="text/javascript"> function searchColumn() { var searchText = document.getElementById('searchTerm ...

Python and Javascript clashing with one another

(Updated question for clarity). I am currently developing a flask app game that involves users inputting guesses via the web browser. The backend, which runs on Python, checks these guesses and provides feedback to the user about their accuracy. Additional ...

Mapbox GL JS stops displaying layers once a specific zoom level or distance threshold is reached

My map is using mapbox-gl and consists of only two layers: a marker and a circle that is centered on a specific point. The distance is dynamic, based on a predefined distance in meters. The issue I'm facing is that as I zoom in and move away from the ...

What is the method for altering the value of a variable within a function?

Is there a way to update the value of a variable? I attempted the method below, but unfortunately, it was unsuccessful: function UpdateData() { var newValue = 0; $.ajax({ url: "/api/updates", type: &quo ...

What is the best way to use Jquery to enclose a portion of a paragraph text within a

How can I wrap the content inside a span that comes after another span, inside a paragraph and a new span? To further illustrate this, consider the following example: <p>foo <span>bar</span> baz</p> The desired outcome is: <p& ...

A Smarter Approach to Updating Text Dynamically with JavaScript and Vue

Currently, I am utilizing Vue to dynamically update text by using setInterval() in combination with a data property. The method I have in place is functional, but I am curious if there exists a more efficient way to optimize it. Is the current code as stre ...