Can the arrangement of parents and children within an object containing items be modified?

Behold, I possess an intricate object structured as follows:

sum = {
  value:{ 
      a: 10,
      b: 11
  }
  value2:{ 
      a: 33,
      c: 12
  }
  ..
}

Delving deeper into the complexity of my object reveals that each letter harbors unique objects with varying values. Yet, the ultimate goal is to traverse through all letters present in each value and generate outcomes akin to the following:

a:{
  value: 10,
  value2: 33
}

The conventional method would involve iterating through the entire structure to construct a new object. However, is there a more streamlined approach to essentially "flip" the order of objects?

Specifically, I seek to utilize solely the keys shared across all value-objects. While currently obtaining them like this, it remains non-essential:

value = ['value', 'value2']
tags.forEach( (tag) =>
    keys.push(Object.keys(sum[tag]))
)
matches = _.intersection.apply(_, keys);


matches.forEach( (match) => {
  ...
}

Answer №1

This approach involves a reorganization of the sequence in which the properties are listed.

grouped[kk][k] = sum[k][kk] for each element

var sum = {
        value: {
            a: 10,
            b: 11
        },
        value2: {
            a: 33,
            c: 12
        }
    },
    grouped = {};

Object.keys(sum).forEach(function (k) {
    Object.keys(sum[k]).forEach(function (kk) {
        grouped[kk] = grouped[kk] || {};
        grouped[kk][k] = sum[k][kk];
    });
});
document.write('<pre>' + JSON.stringify(grouped, 0, 4) + '</pre>');

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

Nashorn poses a security threat due to its ClassFilter vulnerability

Encountering some troubles with Nashorn and came across a concerning security vulnerability highlighted here: It appears that someone can easily execute code using this command: this.engine.factory.scriptEngine.eval('java.lang.Runtime.getRuntime().ex ...

A guide on displaying modal content in PHP using the CodeIgniter framework

When attempting to print the content inside of a modal, pressing ctrl+p causes the modal and backside page to merge. How can I ensure that only the content inside the modal is printed without any merging? Any advanced solutions would be greatly appreciat ...

Adding Numerous Elements to a Container

In my HTML code, there is a div element with the id of controls. I am attempting to add a div containing 2 input fields using this method: this.controls = controlBtns .append('div') .classed({'time-container': true}) .appe ...

Using JavaScript to call a PHP file as the source file

I'm curious about the scenario where a .php file is called as a javascript. What does this signify and in what situations would it be necessary to use such an approach? Example: <head> <script src="dir/myphpfile.php" type="text/javascript" ...

Why isn't my textarea in jQUERY updating as I type?

On my website, I have a comment script that is not functioning correctly in some parts of the jQuery/JavaScript code. Instead of posting an edited comment to PHP, I created a notification window to test if the value passed through is actually changing. W ...

How can you extract the contents of a div tag that includes an image tag using regular expressions in JavaScript?

I have a string that was generated with the following content tesgddedd<br> <div><img style="max-width: 10rem;" src="folder/mypicture.jpg"><div> <br></div></div> My goal is to target the div co ...

Streamline the testing process to ensure compatibility with jQuery version 2.x

I currently have a substantial JavaScript code base that is all built on jQuery 1.8. I am planning to upgrade to jQuery 2.1 in the near future and I am fully aware that many parts of my code will likely break during this process. Is there any efficient me ...

Using Selectpicker with Jquery .on('change') results in the change event being triggered twice in a row

While utilizing bootstrap-select selectpicker for <select> lists, I am encountering an issue where the on change event is being triggered twice. Here is an example of my select list: <select class="form-control selectpicker label-picker" ...

What is the best way to fill out a mandatory text field within the text area?

I am currently facing a challenge with making the comment field mandatory in my PHP application. Despite my lack of expertise, I have been unsuccessful in finding a solution so far. Below is an example code snippet where PHP generates the comment field. Du ...

The NEXT_LOCALE cookie seems to be getting overlooked. Is there a mistake on my end?

I am looking to manually set the user's locale and access it in getStaticProps for a multilingual static site. I have 2 queries: Can a multilingual website be created without including language in the subpath or domain? Why is Next misinterpreting m ...

Maintaining the selected radio button based on previous input with the use of jQuery or PHP

I am in the process of developing an online quiz system. I am fetching questions and options from getquestion.php through ajax on quiz.html. On this page, I've included next and previous buttons so that users can navigate through the quiz. However, I& ...

Ways to emphasize the current tab on the site's navigation bar?

Here's my question: I have a menu with different items, and I want to make sure that the active tab is highlighted when users switch to another page. I noticed that Stack Overflow uses the following CSS: .nav { float: left; font-size: 1 ...

A guide to launching Windows Explorer with JavaScript (Windows+E)

Is there a way to programmatically open Windows Explorer (Windows+E) using JavaScript? ...

Generating a JSON report for mocha test report using babel-cli script

Currently, I am utilizing mocha and babel-cli to execute my mocha tests with the following script: "mocha --compilers js:babel-core/register --recursive" Interestingly, when I do not use babel, I can successfully generate a JSON report using this script: ...

I am able to fill in the ServiceType field, but I am struggling to find the correct options for the ServiceName dropdown menu

Is there a way to dynamically update the ServiceName dropdown options based on the selected value in the ServiceType dropdown? $scope.ServiceTypeAndName = [ { "id":0, "type":"", "list":"" }, { "id":1, "ty ...

Using jQuery to parse JSON transforms an array into a hash object

I recently encountered an issue with a string that I needed to convert into a JSON object. The string looked like this: string = '{ "key": [ { "foo": "bar" } ] }'; To convert the string, I used: json = $.parseJSON(string); However, after co ...

Stop or terminate all ongoing requests in AngularJS

When switching routes, I want to prevent any pending requests from the previous route in order to avoid issues where responses from the previous route interfere with data on the current route. This sometimes happens when responses from the previous route t ...

Access the input field value with PHP and store it in a variable

I previously looked into this issue, but the solution provided in the accepted answer did not resolve it for me: How to get input field value using PHP Below is an excerpt from my result.php file: ... <th> <form name="form" action= ...

Guide to achieving a powerful click similar to a mouse

I've been struggling to get an audio file to play automatically for the past three days, but so far I haven't had any luck. The solutions I've tried didn't work in my browser, even though they worked on CodePen. Can anyone help me make ...

Show the text area content in an alert when using Code Mirror

When I try to alert the content of a textarea that is being used as a Code Mirror on a button click, it appears blank. However, when I remove the script for Code Mirror, the content displays properly. I am puzzled about what could be causing this issue wi ...