parsing and building a sophisticated JSON object

i have a complex array structure as shown below,

array=[ 
  { 'mm': '1', exp: 'exp1' },
  { 'mm': '2', exp: 'exp2' },
  { 'mm': [ '1', '3', '7' ], exp: 'exp3' },
  { 'mm': [ '1', '2', '4', '6' ], exp: 'exp4' },
  { 'mm': [ '1', '3', '2' ], exp: 'exp5' },
  { 'mm': [ '8', '2', '9' ], exp: 'exp6' },
  { 'mm': [ '4', '7', '1', '2' ], exp: 'exp7' },
  { 'mm': [ '5', '6', '2', '4', '3', '8', '1' ], exp: 'exp8' } 
]

i am looking for a way to restructure this array by flipping keys with values and vice versa. The expected output should look like this:

    [ 
      { 'mm': '1', exp: ['exp1','exp3','exp4',','exp5','exp7','exp8'] },
      { 'mm': '2', exp: ['exp2','exp4','exp5','exp6','exp7','exp8'] },
      { 'mm': '3', exp: ['exp3','exp5','exp8'] },
      { 'mm':'4', exp:['exp4','exp7','exp8'] },
      { 'mm':'5', exp:['exp8'] },
      { 'mm':'6', exp:['exp4','exp8'] },
      { 'mm':'7', exp: ['exp3','exp7'] },
      { 'mm':'8', exp: ['exp6','exp8] },
      { 'mm':'9', exp: ['exp6'] }
] 

i would appreciate any efficient solutions or suggestions while i continue working on solving this problem myself.

Answer №1

This implementation utilizes a pair of nested loops along with an object for storing references to the correct element in the final array.

var data = [{ 'mm': '1', exp: 'exp1' }, { 'mm': '2', exp: 'exp2' }, { 'mm': ['1', '3', '7'], exp: 'exp3' }, { 'mm': ['1', '2', '4', '6'], exp: 'exp4' }, { 'mm': ['1', '3', '2'], exp: 'exp5' }, { 'mm': ['8', '2', '9'], exp: 'exp6' }, { 'mm': ['4', '7', '1', '2'], exp: 'exp7' }, { 'mm': ['5', '6', '2', '4', '3', '8', '1'], exp: 'exp8' }],
    pivot = function (data) {
        var result = [], refObj = {};
        data.forEach(function (item) {
            [].concat(item.mm).forEach(function (value) {
                if (!refObj[value]) {
                    refObj[value] = { mm: value, exp: [] };
                    result.push(refObj[value]);
                }
                refObj[value].exp.push(item.exp);
            });
        });
        return result;
    }(data);

document.write('<pre>' + JSON.stringify(pivot, 0, 4) + '</pre>');

Answer №2

I'm not entirely clear on what you mean by 'cannot hardcode any values', but I wanted to provide an illustrative solution nonetheless. This code snippet is not optimized for performance, but rather aims to showcase a general approach.

var data =[ 
  { 'mm': '1', exp: 'exp1' },
  { 'mm': '2', exp: 'exp2' },
  { 'mm': [ '1', '3', '7' ], exp: 'exp3' },
  { 'mm': [ '1', '2', '4', '6' ], exp: 'exp4' },
  { 'mm': [ '1', '3', '2' ], exp: 'exp5' },
  { 'mm': [ '8', '2', '9' ], exp: 'exp6' },
  { 'mm': [ '4', '7', '1', '2' ], exp: 'exp7' },
  { 'mm': [ '5', '6', '2', '4', '3', '8', '1' ], exp: 'exp8' } 
];

var tempData = {};
var newData = [];

data.forEach(function(dataPoint) {
    var arrPoint = {
        mm: [].concat(dataPoint.mm),
        exp: [].concat(dataPoint.exp)
    };

    arrPoint.mm.forEach(function (code) {
        if (!tempData[code]) {
            tempData[code] = {
                mm: code,
                exp: []
            }
        }

        var vals = tempData[code].exp;

        arrPoint.exp.forEach(function(val) {
            if (vals.indexOf(val) === -1) {
                vals.push(val);
            }
        });

    });
});


for (var propName in tempData) {
    if (tempData.hasOwnProperty(propName)) {
        newData.push(tempData[propName]);
    }
}

document.write(JSON.stringify(newData));

Next time, it's probably best if you try tackling the problem on your own first before seeking help. This way, your question can be more specific and targeted.

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

Javascript build a list of location classifications

I'm attempting to create a list of categories from an array of objects named places, here is what I have tried: this.places.forEach((p) => { p.categories.forEach((c) => { if(!this.categories.some(c ...

Vuejs: Limiting the number of items in an li tag to 5

selectPreviousSearch(index) { this.search = this.searchHistory[index]; this.showSearchHistory = false; }, <input class="form-control bg-light-blue" id="SearchText" type="text" v-model="search" @keydown.enter = 'ent ...

Creating space between flex items in Slick Carousel with Vue

This is my current Slick Carousel. There are 4 items in a row, and I am looking to insert some margin between each item while maintaining the existing aspect-ratio: 1.3/1; I'm struggling with overriding the classes from vue-slick-carousel. Does any ...

The Django CSRF token is inaccessible for retrieval

I'm in the process of developing a website using Vue.js for the frontend and Django for the backend. I've made sure to include the csrf token in every request from the frontend to the backend to prevent any 403 Forbidden errors. All requests are ...

What is the process of including a pre-existing product as nested attributes in Rails invoices?

I've been researching nested attributes in Rails, and I came across a gem called cocoon that seems to meet my needs for distributing forms with nested attributes. It provides all the necessary implementation so far. However, I want to explore adding e ...

Issue with the recursive function in javascript for object modification

I have all the text content for my app stored in a .json file for easy translation. I am trying to create a function that will retrieve the relevant text based on the selected language. Although I believe this should be a simple task, I seem to be struggl ...

When using Angular2, I have found that I am unable to extract the body data from JSONP responses. However, I have discovered that this issue

Initially, I developed the SERVER using spring-boot framework. The code for this looks like: public class App { @RequestMapping("/") @ResponseBody String home(HttpServletRequest request) { String aa=request.getParameter("callback"); System.out.pri ...

What is the optimal value for the variable x in this scenario?

What is the correct value for X to make this condition valid? // Your code goes here if (x == 1 && x === 2) { console.log('Success!'); } ...

search through an object to find specific data

Here is a JavaScript object that I have: var data = { "type": [ "car", "bike" ], "wheels": [ "4", "2" ], "open": [ "Jan", "Jan" ] ...

The ajaxForm function is failing to execute properly and is not providing any error messages

When trying to use jQuery ajaxForm, I encounter a strange issue. I am attempting to set up a form for file upload with progress percentage tracking. However, my ajaxForm function does not seem to be triggering at all. Below is the code snippet I am usin ...

Using jQuery to retrieve the id with [id^=''] when making an AJAX request, then populating and generating a table based on the retrieved data

In my jQuery code, I am using AJAX to fetch data and then creating a simple table with that data. Here is an example: $.ajax({ method: 'GET', url: '/analyzePage/searchTag/' + tagName, contentType: false, processData: fa ...

Restful Spinner

app.config(function(RestangularProvider) { RestangularProvider.addRequestInterceptor(function(element) { console.log("Request initiated"); return element; }); RestangularProvider.addResponseInterceptor(function(data) { ...

What could be the reason for getElementsByClassName failing to work on dynamic HTML elements?

I'm currently in the process of generating multiple dynamic HTML tables and assigning a class to each one. Here's an example: var x = document.createElement("TABLE"); x.className = "table_pos_parts"; //var row = x.insertRow( ...

Silly problem arising from the animate feature in jQuery

Apologies for my poor English. I am facing an issue with the animate function of jQuery in my code snippet. It seems to work fine at line 2, but it doesn't work at line 3. Can someone help me understand why? $('.opac').hover(function(){ ...

Restrict access to table records by specifying an array of row identifiers

Hi everyone, I've encountered a small issue. Just to provide some background, I have a table with checkboxes. Each row in the table has an associated ID, and when selected, I receive an array like this: const mySelectedRoles = [1997, 1998, 1999] Once ...

Explore the titles provided by Wikipedia

Hi there, I'm fairly new to Angular and trying to work with the Wikipedia API. However, I seem to be having trouble getting 4 titles from the API. Here's an example URL for one of the titles: https://en.wikipedia.org/w/api.php?action=query&pr ...

What could be the reason for the discrepancy between the values displayed in the two alerts? What is causing this difference in

Check out this JavaScript code snippet: var x = 3; var foo = { x: 2, baz: { x: 1, bar: function() { return this.x; } } } var go = foo.baz.bar; alert(go()); alert(foo.baz.bar()); When you run the two alert functions here, you&ap ...

The use of DefaultAnnotationHandlerMapping in the dispatcher.xml file is no longer recommended

Why have org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter and org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping been deprecated in mvc-dispatcher.xml? Any assistance would be greatly appreciated. T ...

Having trouble getting the Keycloak provider to work with Next-Auth?

It's puzzling to me why my next-auth integration with Keycloak server is failing while the integration with Github is successful. import NextAuth from "next-auth" import KeycloakProvider from "next-auth/providers/keycloak"; import ...

Button click functionality for updating in Classic ASP is functioning correctly exclusively in Internet Explorer and not in other web browsers

Currently, I am in the process of enhancing a Classic ASP application. Within this application, there is an HTML table that is populated from a SQL database. One cell within the table contains checkboxes. Upon clicking one of these checkboxes, a popup wind ...