Combine objects where the keys match

I am unfamiliar with typescript and node.js, and I am attempting to merge the JSON array below. Please note that I am unsure if the client allows for new dependencies or plugins. Is it possible to achieve this without using underscore or jQuery extend?

[ { parentauthscopekey: 1, childauthscopekey: 2 },
  { parentauthscopekey: 12, childauthscopekey: 10 },
  { parentauthscopekey: 12, childauthscopekey: 11 },
  { parentauthscopekey: 13, childauthscopekey: 1 } ]

Desired Output:

[ { parentauthscopekey: 1, childauthscopekey: [ 2, 1 ] },
  { parentauthscopekey: 12, childauthscopekey: [ 10, 11, 12 ] },
  { parentauthscopekey: 13, childauthscopekey: [ 1, 13 ] } ]

I have attempted the code below, it works but it is lengthy. I am hoping for a simpler solution without manually specifying scope and scopeMap values.

 table = [ { parentauthscopekey: 1, childauthscopekey: 2 },
  { parentauthscopekey: 12, childauthscopekey: 10 },
  { parentauthscopekey: 12, childauthscopekey: 11 },
  { parentauthscopekey: 13, childauthscopekey: 1 } ]
   
    scope=[1,12,13]
    scopeMap = new Set()

    table2 = []
    scope.forEach(parentauthscopekey => {
        table.forEach(row =>{
            if(row.parentauthscopekey == parentauthscopekey && !scopeMap.has(parentauthscopekey))
            {
                scopeMap.add(parentauthscopekey)
                childauthscopekey = []
                table.filter(c => c.parentauthscopekey == row.parentauthscopekey).forEach(r=>{
                    childauthscopekey.push(r.childauthscopekey)
                })
                childauthscopekey.push(parentauthscopekey)
                table2.push({parentauthscopekey, childauthscopekey})
            }
        })
    })
    console.log(table2)

Answer №1

Here is a solution for your problem:

  • Utilize the array.reduce method to create the desired data structure
  • Retrieve each entry with a child matching parentauthscopekey using array.filter
  • Add the current parentauthscopekey to childauthscopekey

var data = [ { parentauthscopekey: 1, childauthscopekey: 2 },
  { parentauthscopekey: 12, childauthscopekey: 10 },
  { parentauthscopekey: 12, childauthscopekey: 11 },
  { parentauthscopekey: 13, childauthscopekey: 1 } ];
  
var result = data.reduce((acc, current) => {
    if (!acc.some(one => one.parentauthscopekey === current.parentauthscopekey)) {
      var childs = data.filter(one => one.parentauthscopekey === current.parentauthscopekey).map(one => one.childauthscopekey);
      childs.push(current.parentauthscopekey);
      acc.push({
        parentauthscopekey: current.parentauthscopekey,
        childauthscopekey: childs
      })
    }
  return acc;
}, []);

console.log(result);

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

Forward user to a subdomain once they have successfully logged in on an Angular 2 application

I've been working on an Angular 2 application and I'm looking to redirect users from www.example.com to admin.example.com after they successfully log in. What is the best way to accomplish this using Angular 2? Additionally, how can I test this f ...

Consolidation of JSON log files

     If you have a file containing line-delimited JSON records: {"id": 1, "position": 1234} {"id": 2, "position": 23} {"id": 3, "position": 43} {"id": 1, "position": 223} I want to streamline this file by only retaining the last record for each id. F ...

passing JSON data using JavaScript or jQuery

I have a JSON snippet that I need to parse using JavaScript or jQuery and convert into variables: name and meetup. Can you help me with this? Below is the JSON code: { "MYID": 1, "module": [ { "name": "Manchester", ...

Tips for concealing a class within JavaScript

I am looking for a way to hide a specific shipping class for products that qualify for free postmail delivery. Here is the scenario: If a product with the following link: is added to the cart and it belongs to this shipping class: shipping_method_0_adva ...

Implementing a document update event using jQuery

On my WordPress site, I am using a responsive lightbox plugin. When an image is clicked, it opens a popup box with the ID fullResImage. Now, I would like to incorporate the Pinch Zoomer function to it. Do I need to bind a function for this, or is there a s ...

Error in Nightwatch.js: window object does not exist

I am currently attempting to utilize Nightwatch for testing a React application that is integrated with React-Router. Upon running my test with Nightwatch, I have encountered an issue where window appears to be undefined. In order to verify the availabil ...

Protractor unexpectedly giving back a promise instead of the expected attribute value

I'm facing a challenge where I am attempting to extract the value of an HTML attribute and store it in a variable named url_extension. However, instead of getting the desired value, I keep receiving a Promise object. Below is my code snippet: (Please ...

Problem encountered when using multiple tags for the table of contents

My script generates a table of contents based on the headings h2 and h3. The issue arises when there is a span tag within an h2, causing the script to skip that heading and not create a link for it. I suspect the problem lies in the regular expression /< ...

How to deselect a checkbox using AngularJS

I have a checklist of items <input type="checkbox" ng-model="servicesModel" value={{item.name}} id={{item.name}} ng-click="toggleSelection(item.name)"/> and I need to unselect the currently selected checkbox $scope.toggleSelection = function toggl ...

Arrange a PHP array based on various values found within subarrays

Unsure if the title fits perfectly, but this is how the array appears: array ( [0] => array ( [category] => 'Value_1' [date] => '01/01/2011' [data] => 'A' ...

Using Gson in Java to deserialize JSON into a child class

I have designed an abstract class specifically for handling configuration files in my project. This class can be extended by numerous other classes to customize configurations. I have successfully implemented the functionality to save these configurations ...

Converting JavaScript to PHP and encountering problems with POST encoding

Trying to send a string from JavaScript on the client-side to a PHP script on the back-end. The string has special quotes like ’ and “. When checking the console in Chrome, the POST headers show these special characters as they are. On the PHP side, I ...

How to reach a restricted method in C#

Hello everyone! I am new to the world of C# and encountering an issue. I have created an array in the Form_Load method of my program, but I need to access the array in a picture_box method like this: private void Form2_Load(object sender, EventArg ...

Error encountered: Unable to remove certain elements from the array

http://jsfiddle.net/83m3B/ I am facing an issue where I am trying to remove certain elements from an array using the data-object-id attribute. However, when I implement it, the loop does not function as expected and seems to skip over an element each time ...

CRITICAL ISSUE: Mark-compact processes not performing effectively close to heap capacity

I encountered an error and I'm seeking a brief explanation to help me understand what needs to be fixed. This error occurs during the compilation of TypeScript. <--- Last few GCs ---> [1791:0x5533880] 72626 ms: Scavenge (reduce) 2042.8 (2 ...

Contrast the equality of two arrays with objects

I have two different types of data structures var dataA = [ { "Employee Name": "Mr. X", id: "1" }, { "Employee Name": "Mr. Y", id: "2" }, { "Employee Name": "Mr. Z", id: "3" } ]; var dataB = [ { id: "1", " ...

Substitute a section of the image source

Currently, I am facing an issue where a small part of the img src needs to be modified. When an img is uploaded using a free CMS service, the path to save the imgs is stored in a file called www.domain.com. As a result, the code displays the image as <i ...

Is there a way to assign a value to the property in AngularJS' ng-options?

There seems to be a common issue that many people (myself included) are facing. When utilizing the ng-options directive within AngularJS to populate the choices for a <select> element, I am struggling to understand how to assign a value to each opti ...

Laravel controller is throwing an error stating that the argument for the foreach() function must be of type array or object

I am receiving an error message "foreach() argument must be of type array|object" in my Laravel controller while trying to show comments in a post. Below is the code snippet: Blade File @foreach($comment->product_images as $image) <a href="{{a ...

Change the input field to uppercase using JavaScript but do not use inline JavaScript

Hey there! I have a basic script set up (see below) with an input field allowing users to enter a query. This query is then sent to a socrata webservice to request specific data, which is displayed in an alert box. So far, everything works smoothly. var l ...