Transform object into distinct entities based on their individual key value pairs

Here is my unique combined entity:

{
      "levelId-0":1,
      "level-0":"1",
      "levelpoints-0": 15,      
      "levelId-1":2,
      "level-1":"2",
      "levelpoints-1": 15,
      "levelId-2":3,
      "level-2":"3",
      "levelpoints-2": 15,
      "levelId-3":4,
      "level-3":"4",
      "levelpoints-3": 15,
      "medalId-0":1,
      "medalName-0":"Bronze",
      "medalsPoint-0":2020,
      "medalId-1":2,
      "medalName-1":"Silver",
      "medalsPoint-1":10,      
      "medalId-2":3,
      "medalName-2":"Gold",
      "medalsPoint-2":10,
      "medalId-3":1003,
      "medalName-3":"Platinum",
      "medalsPoint-3":85
   }

Desired Outcome:

      {
        "Level":[
          {
            "levelId":1,
            "level":"1",
            "points":2020
          },
          {
            "levelId":2,
            "level":"2",
            "points":1000
          }
        ],
        "Medal":[
          {
            "medalId":1,
            "medalName":"Bronze",
            "points":2020
          },
          {
            "medalId":3,
            "medalName":"Gold",
            "points":1000
          }
        ]
      }

Is there anyone who can assist me with this? I have attempted various methods without success. I looked into this solution: SO

Answer №1

To extract the keys of the outer objects and parse the key of the provided data into a property and an index for assignment, you can follow this approach:

var data = { "levelId-0": 1, "level-0": "1", "levelpoints-0": 15, "levelId-1": 2, "level-1": "2", "levelpoints-1": 15, "levelId-2": 3, "level-2": "3", "levelpoints-2": 15, "levelId-3": 4, "level-3": "4", "levelpoints-3": 15, "medalId-0": 1, "medalName-0": "Bronze", "medalsPoint-0": 2020, "medalId-1": 2, "medalName-1": "Silver", "medalsPoint-1": 10, "medalId-2": 3, "medalName-2": "Gold", "medalsPoint-2": 10, "medalId-3": 1003, "medalName-3": "Platinum", "medalsPoint-3": 85 },
    result = Object.entries(data).reduce((o, [k, v]) => {
        var key = ['Level', 'Medal'].find(s => k.includes(s.toLowerCase())),
            [prop, index] = k.split('-');

        o[key] = o[key] || [];
        o[key][index] = o[key][index] || {};
        o[key][index][prop] = v;
        return o;
    }, {});

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

Answer №2

var info = {
  "levelId-0": 1,
  "level-0": "1",
  "levelpoints-0": 15,

  "levelId-1": 2,
  "level-1": "2",
  "levelpoints-1": 15,

  "levelId-2": 3,
  "level-2": "3",
  "levelpoints-2": 15,

  "levelId-3": 4,
  "level-3": "4",
  "levelpoints-3": 15,

  "medalId-0": 1,
  "medalName-0": "Bronze",
  "medalsPoint-0": 2020,

  "medalId-1": 2,
  "medalName-1": "Silver",
  "medalsPoint-1": 10,

  "medalId-2": 3,
  "medalName-2": "Gold",
  "medalsPoint-2": 10,

  "medalId-3": 1003,
  "medalName-3": "Platinum",
  "medalsPoint-3": 85
};

console.log(Object.entries(
  Object.keys(info).reduce(
    (output, key) => {
      let group = key.slice(-1);
      if(key.startsWith("level") && !(!((output["level"][group] = output["level"][group] || {})[key] = info[key])){
      key.startsWith("medal")) !== (!(output["medal"][group] = output["medal"][group] || {})[key] = info[key]);
        return output;
    },
    { level: {}, medal: {} }
  )
).reduce((output, item) => (p[item[0]] = Object.values(item[1]),p),{}));

Answer №3

Check out this handy solution for your problem. Hopefully, this will resolve the issue you're facing.

var obj = {
      "levelId-0":1,
      "level-0":"1",
      "levelpoints-0": 15,      
      "levelId-1":2,
      "level-1":"2",
      "levelpoints-1": 15,
      "levelId-2":3,
      "level-2":"3",
      "levelpoints-2": 15,
      "levelId-3":4,
      "level-3":"4",
      "levelpoints-3": 15,
      "medalId-0":1,
      "medalName-0":"Bronze",
      "medalsPoint-0":2020,
      "medalId-1":2,
      "medalName-1":"Silver",
      "medalsPoint-1":10,      
      "medalId-2":3,
      "medalName-2":"Gold",
      "medalsPoint-2":10,
      "medalId-3":1003,
      "medalName-3":"Platinum",
      "medalsPoint-3":85
   }
   
   var yourObj = {
   "level":[],
   "medal":[]
   }
   
   var values =[];
   
   for (key in obj){
          var keyval = key.split('-')  
      
          if(!values[keyval[1]]){
           values[keyval[1]] =[]
          }
         
          values[keyval[1]].push(keyval)
   }
   
  for (i =0;i<values.length;i++){
   var  tempLevelObj = {
            "levelId":"",
            "level":"",
            "points":""
          };
 var tempMedalObj = {
            "medalId":"",
            "medalName":"",
            "points":""
          }
          

  for(j=0;j<values[i].length;j++){

   var joinVal = values[i][j].join('-')
  
   switch(values[i][j][0]){
   case 'levelId' :tempLevelObj.levelId = obj[joinVal] ;break
   case 'level' : tempLevelObj.level = obj[joinVal] ;break
   case 'levelpoints' :tempLevelObj.points = obj[joinVal] ;break
   case 'medalId' :tempMedalObj.medalId = obj[joinVal] ;break
   case 'medalName' :tempMedalObj.medalName = obj[joinVal] ;break
   case 'medalsPoint' :tempMedalObj.points = obj[joinVal] ;break
   }
  
  }
  yourObj.level.push(tempLevelObj)
  yourObj.medal.push(tempMedalObj)
  }
  
  console.log(yourObj)

Answer №4

give this a shot

function displayJson() {
    function updateObject(properties, keyPath, data) {
        properties.set(keyPath, data);
    }

    var objMap = new Map(),
        jsonResult = {};
    // iteration is needed here based on your specific needs
    updateObject(objMap, 'product.productId', 12345);
    updateObject(objMap, 'product.name', 'Sample Product');
    updateObject(objMap, 'product.price', '$19.99');

    objMap.forEach((data, path) => {
        var keysArr = path.split('.'),
            lastKey = keysArr.pop();
        keysArr.reduce((acc, curr) => acc[curr] = acc[curr] || {}, jsonResult)[lastKey] = data;
    });

    console.log(jsonResult);
    // you can also choose to return the generated JSON object
}

Answer №5

I believe that the expected outcome provided is inaccurate. In my opinion, the correct expected output would be:

{
  "Grade": [
    {
      "gradeId": 1,
      "grade": "A",
      "score": 95
    },
    {
      "gradeId": 2,
      "grade": "B",
      "score": 85
    },
    {
      "gradeId": 3,
      "grade": "C",
      "score": 75
    }
  ],
  "Award": [
    {
      "awardId": 1,
      "awardName": "Bronze",
      "points": 2020
    },
    {
      "awardId": 2,
      "awardName": "Silver",
      "points": 10
    },
    {
      "awardId": 3,
      "awardName": "Gold",
      "points": 10
    }
  ]
}

Below is the code snippet to generate the desired output:

var abc = {
    "gradeId-0": 1,
    "grade-0": "A",
    "gradescore-0": 95,
    "gradeId-1": 2,
    "grade-1": "B",
    "gradescore-1": 85,
    "gradeId-2": 3,
    "grade-2": "C",
    "gradescore-2": 75,
    "gradeId-3": 4,
    "grade-3": "D",
    "gradescore-3": 65,
    "awardId-0": 1,
    "awardName-0": "Bronze",
    "awardsPoint-0": 2020,
    "awardId-1": 2,
    "awardName-1": "Silver",
    "awardsPoint-1": 10,
    "awardId-2": 3,
    "awardName-2": "Gold",
    "awardsPoint-2": 10,
    "awardId-3": 1003,
    "awardName-3": "Platinum",
    "awardsPoint-3": 85
};
var final = {
    "Grade": [],
    "Award": []
};
let abcKeys = Object.keys(abc);
var lastRowIndex = parseInt(abcKeys[abcKeys.length - 1].split('-')[1]); //3
for (let i = 0; i < lastRowIndex; i++) {
    let gradeObj = {}, awardObj = {};
    gradeObj['gradeId'] = abc['gradeId-' + i];
    gradeObj['grade'] = abc['grade-' + i];
    gradeObj['score'] = abc['gradescore-' + i];
    awardObj['awardId'] = abc['awardId-' + i];
    awardObj['awardName'] = abc['awardName-' + i];
    awardObj['points'] = abc['awardsPoint-' + i];
    final.Grade.push(gradeObj);
    final.Award.push(awardObj);
}
console.log('--final--', final);

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

Configuring routers for my node.js application

I've been facing several challenges with setting up the routes for my node.js application. Below is a snippet of my app.js file where I call the route. const express = require("express"); const bodyParser = require("body-parser"); const app = exp ...

remove information within callback

I came across this code snippet and encountered an issue while trying to clear the comment from within the response. I'm seeking assistance in figuring out how to resolve this problem. app.controller('CommentController', function($scope, $h ...

What is the best method for replacing the current page in an Ionic app?

I am facing an issue with the following navigation flow: User lands on the Contacts page -> clicks on a button to navigate to the NewContact page using navController.push() method -> from there, user is directed to the ContactCreated page. How can ...

Determining the parameter type of an overloaded callback: A comprehensive guide

I am currently working on creating a type-safe callback function in TypeScript with a Node.js style. My goal is to define the err parameter as an Error if it exists, or the data parameter as T if not. When I utilize the following code: export interface S ...

Double execution of JavaScript function when Enter key is pressed

In my HTML page, I have a button that looks like this: <input id="btnLogin" class="loginBtn" type="button" value="Login" title="Login" /> I've set up a jQuery click event for this button: $('#btnLogin').click(function () { Vali ...

Scheduled task running a PHP script which executes a separate PHP script

Currently, I have a PHP script that is executed server side through a CRON job every 60 seconds. However, I require it to run every 10 seconds instead. Is it feasible for me to create a separate "Timer.PHP" file that would trigger the UPDATE.PHP script and ...

Decoding JSON information using JQuery/JavaScript

I came across a similar discussion on this topic here, however, the format of my returned data is slightly different. The Json string returned from the server looks like this: <!DOCTYPE HTML> <html> <head> <style> </style> ...

What's preventing my Angular list from appearing?

I am currently developing an Angular project that integrates Web API and entity framework code first. One of the views in my project features a table at the bottom, which is supposed to load data from the database upon view loading. After setting breakpoin ...

Unable to properly cancel a post request using abort functionality

In the process of building a Next.js app, I encountered an issue with calling a post request. I included a cancel button to halt the post request, and attempted to use abortController in conjunction with Axios (v1.4.0) to achieve this. Even though the &ap ...

I need to extract particular information from a JSON file and include it in another JSON file or variable

Hey there, I'm looking to retrieve specific data from an API and store it in a file. The API I am interested in is quite large, so I only want to extract certain information for each item, such as the 7-day price. However, when I attempt to use an emp ...

The content is spilling over onto the navigation bar

I am facing an issue with my blog site that I created using Django. The problem arose after adding a navigation bar, as the content of the website is overlapping the navigation bar when I scroll down the page. If you have any suggestions on how to add a ...

Is it possible to submit a HTML5 form and have it displayed again on the same page?

Is it possible to simply reload the sidebar of a page containing an HTML5 form upon submission, or is it necessary to load a duplicate page with only the sidebar changed? I am unsure of how to tackle this situation; firstly, if it is achievable in this m ...

React Native Issue - Invariant Violation: Invalid Element Type

Currently, I am enrolled in a Udemy course where I am learning to develop a demo react native application. The project includes three main components - App, AlbumList, & AlbumDetail. Below is the code for each component: App.js import React, { Component ...

What is the best way to establish a new JavaScript data type that can be accessed using both key and index?

Looking to create a unique datatype or object in JavaScript that allows access by both index and key, as well as having a length property to display the number of items in the datatype. Something along the lines of: MyDataType[0].name="John" MyDataType[0 ...

What is the best way to save a JavaScript object or JSON within an HTML element using the HTML5 data attribute?

I have an anchor element and I want to store and retrieve the object within it in this specific format. <a id ="test" data-val="{key1:val1,key1:val1}"> </a> When saved in this manner, fetching it with $("#test").data('val') returns ...

Adding a jPlayer on the fly

I've been working on a code snippet to dynamically add jPlayers through a function. Here is the code I have so far: function audio_player(audio, title, type) { var id = $('.audio').length; $('#audio').append('<di ...

Javascript encountered an error upon attempting to return from the main function

I have a function that calls the database to perform an action: function callQuery(query) { db.query(query, (err, res) => { if (err) { // Error connecting to DB console.log(err.stack) } else { // Return the results ret ...

Creating JavaScript object fields with default values in an AngularJS model: A Step-by-Step Guide

As I work on developing the model layer for my AngularJS application, I came across some valuable advice on using functions to create objects. This source emphasizes the use of functions like: function User(firstName, lastName, role, organisation) { // ...

What could be causing this JSON file to be displaying in an unusual manner?

I am currently working with a JSON document that has been validated using JSlint. The JSON data is structured like this: [{ "date": "2017-02-10", " action": "Do a thing", "state": "closed", "url": "https:someurl.com" }, .... Additionall ...

Merging Data with mongoDB

Just starting out with MongoDB, I have developed an app that functions similar to Twitter with followers and following. Here is the schema I am working with: UserSchema : username:'Alex', pass:'salted', likes:'200&ap ...