Combining JSON Objects in a Formatted Manner

I'm working with two variables:

var parentData: [{
  "ID": "869",
  "Name": "John"
}, {
  "ID": "800",
  "Name": "Jane"
}]
var Cost = [{
  "Number": "869",
  "Amount": 100
}, {
  "Number": "800",
  "Amount": 200
}, {
  "Number": "800",
  "Amount": 560
}]

I wish to achieve the following updated result:
{
  "parentData": [{
      "ID": "869",
      "Name": "John",
      "Costs": [{
          "Number": "869",
          "Amount": 100
        },
        {
          "Number": "869",
          "Amount": 200
        },
        {
          "NO": "869",
          "Amount": 560
        }
      ]
    },
    {
      "ID": "800",
      "Name": "Mary",
      "Costs": [{
          "Number": "800",
          "Amount": 100
        },
        {
          "Number": "800",
          "Amount": 200
        },
        {
          "Number": "800",
          "Amount": 560
        }
      ]
    }
  ]
}

Any suggestions on how to accomplish this?

Answer №1

One way to efficiently store the reference to multiple parent elements is by using a hash table.

var parents = [{ ID: "869", Name: "John" }, { ID: "800", Name: "Jane" }],
    costs = [{ ID: "869", Amount: 100 }, { ID: "800", Amount: 200 }, { ID: "800", Amount: 560 }],
    hashTable = Object.create(null),
    output = { Parents: parents.map(function (parent) { return hashTable[parent.ID] = parent; }) };

costs.forEach(function (cost) {
    (hashTable[cost.ID].Costs = hashTable[cost.ID].Costs || []).push(cost);
});

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

Answer №2

I hope this solution meets your needs.

angular.module("app", []).controller("myCtrl", function($scope) {
  $scope.parent = [{
    "SNO": "869",
    "Name": "ABC"
  }, {
    "SNO": "800",
    "Name": "CCC"
  }];

  $scope.Cost = [{
    "NO": "869",
    "Amnt": 100
  }, {
    "NO": "800",
    "Amnt": 200
  }, {
    "NO": "800",
    "Amnt": 560
  }];

  $scope.mergeArr = function(arr1, arr2) {
    var arrTmp = [];
    if (Array.isArray(arr1)) {
      arrTmp.push(...arr1);
    } else {
      arrTmp.push(arr1);
    }

    arrTmp.forEach(function(item) {
      var costArr = arr2.filter(function(item2) {
        return item2.NO === item.SNO;
      });

      if (costArr.length > 0) {
        if (!item.COST) {
          item["COST"] = [];
        }

        costArr.forEach(function(cost) {
          item.COST.push(cost);
        })
      }
    });
    console.log(arrTmp);
    return {
      "Parent": arrTmp
    };
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
  <div>
    <ui>
      <li ng-repeat="project in mergeArr(parent, Cost).Parent">
        {{project.SNO}} - {{project.Name}}
      </li>
    </ui>
  </div>
</div>

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

Exporting a class from an index.ts file may result in a problem where the injected constructor is

Utilizing an index.ts file to manage exports, following the guidelines outlined in the Angular 2 style guide (https://github.com/mgechev/angular2-style-guide/blob/master/old/README.md#directory-structure), has been successful throughout my application deve ...

What could be causing my Dojo Pie chart to vanish when I trigger the updateSeries function following an Ajax request?

I'm currently working on updating a dojo Pie chart using the updateSeries method. The method is called after an ajax request to retrieve an updated JavaScript array data. Below is the JavaScript code: var eventByReasonsData = .... //data is populate ...

What is the purpose of including production dependencies in the package.json file of a React/Redux frontend project?

Recently delving into the world of React.js+Redux, I've noticed that many frontend projects utilize npm as their package manager. Take, for instance, this project - counter. Within this project, there exists a package.json file. Upon examining its c ...

Holding off on triggering a jQuery Ajax request until a function returns a value

I'm currently facing an issue where an Ajax request is not waiting for a function call to return before executing. The specific scenario involves calling getSelectedMessages to retrieve checkbox values and then passing these values in an array to the ...

What is the best way to avoid duplicating this JQM function multiple times and instead reuse it efficiently?

After coming across this interactive demo, I successfully implemented it on my website using JQM. However, in order to activate the panel swipe feature, I had to include the following function: $( document ).on( "pagecreate", "#demo-page", function() { ...

Filtering an array of JSONs in Vue.js using a separate array of JSONs

In my code, there are two arrays of JSONs: one named products and another called deletedProducts. The task is to filter out the products that are not present in the deletedProducts array. For instance: products = [ { id: 1, name: 'Box&apos ...

Every time I attempt to compile NodeJS, I encounter a compilation error

Within mymodule.js var fs = require('fs') var path = require('path') module.exports = function(dir, extension, callback){ fs.readdir(dir, function(error, files){ if(error) return callback(error) else { ...

Is it possible to retrieve the createdAt timestamp without displaying the 'GMT+0000 (Coordinated Universal Time)'?

After conducting an extensive search, I have yet to find a satisfactory answer. My goal is to configure it without including the CUT time. {name: "Registered:", value: `${user.createdAt}`}, {name: "Joined:", value: `${message.guild.joinedAt}`} Presently, ...

Ways to complete a progress bar up to 100% based on the user's specified time

I'm currently developing a progress bar for a pomodoro timer. The concept is for this bar to reach 100% completion based on the specified time of the pomodoro session. For instance, if the session is set for 30 minutes, the progress bar should be full ...

Mongoose Filtering in Rest API: A Comprehensive Guide

Currently, I am utilizing Express to construct an API. Within this API, my objective is to retrieve a list of customers from MongoDB by using Mongoose. The code snippet below showcases the route I have set up (please disregard any paging and limit concerns ...

Adding various react elements to a list with the click of a button: A step-by-step guide

I am faced with a challenge where I have two different types of components that I want to display on the screen when a button is clicked. However, I don't want to simply show and hide the components. Instead, I want to be able to dynamically generate ...

Querying two MongoDB collections simultaneously to locate a user based on their email address

I am working with two different collections, tutors and users, within my MongoDB database. Within the controller, I have a function called signin. In this function, I need to modify the condition so that it searches for a user in both the tutors and users ...

Reloading the table columns in a JSP page with a click of the refresh button on every row using AJAX and JavaScript

Hey there! I have a JSP page with a table where data is displayed by iterating through a list from the action class. Each row in the table has a refresh button at row level. Here is a snippet of the JSP: <script type="text/javascript"> functi ...

"XMLHttpRequest 206 Partial Content: Understanding the Importance of Partial

I need help with making a partial content request using an XMLHttpRequest object in JavaScript. Currently, I am trying to load a large binary file from the server and want to stream it similar to how HTML5 video is handled. While setting the Range header ...

Encountering a getMacChromiumEdgeDriverArchitecture error while using wdio/selenium-standalone-service

As I continue to learn WebDriverIO and adjust to MacOS, I encountered an error while trying to execute a spec file using "npm run test:wdio". The error message is as follows: > [email protected] test:wdio /Users/vinicius.correia/Desktop/dev/automat ...

What is the best way to optimize a search for objects with extensive field arrays?

Recently, I've been working with an object schema that includes an array field to store ids for objects from a separate collection. This array has the potential to contain thousands of ids. Up until now, I have been excluding this field using .select( ...

Is there a way to dynamically change the title of a tab when new content is added to a minimized page?

Is anyone familiar with how websites like Facebook and Buzzfeed update their tab titles when there are multiple tabs open? I have noticed that sometimes they add a "(1)" or "(2)" to indicate changes on the page. Do they use JavaScript to achieve this eff ...

Ways to inspect a number within a span and adjust its color depending on the value?

Can someone help me figure out why this code is not reading the value correctly? Check it out here This is the HTML: <a class="InterestLink">Click me</a> <div id="InterestExpander"> <div id="InterestExpanderX"> ...

Tips for Enhancing Window Leveling (Brightness and Contrast)

const pixelArray = [11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11..] if (pixelArray != null) { for (let i = 0; i < pixelArray.length; i++) { let ...

Retrieve data from the MySQL database based on the search input field and dynamically update the options in the

I'm facing a programming challenge that I perceive to be at an advanced level for me. Currently, I have a custom search field in my registration form. However, I am looking to transform it into a dropdown menu that pulls user values from MySQL databas ...