• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

140
Views
How do I reformat this JSON data by creating a key from a section of the data?

I'd like to reformat data by taking a section of one JSON entry. For example, I have JSON data:

{ "AXD:Condor": 12,
 "AXD:Pelican": 20,
 "GPR:Deer": 15,
 "GPR:Owl": 34
}

and I would like to have reformat it to something like this:

{ AXD:{
     Condor: 12,
     Pelican:20
 }
  GPR:{
     Deer: 15,
     Owl: 34
 }
}

I apologize if this question is obvious or badly worded, I'm quite new to using JSON. Thanks for taking the time to answer.

almost 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Using Object.entries(data) we are getting an array with the key-value pairs of the data object. Then we iterate through this array using reduce, where [key, value] is the object's pair and a is the accumulator whose initial value is an empty object {} (check the end of the function) and will be the result.

Now for each iteration, we split our key value and keep the first part that we want to use as our new key. Then we check if the accumulator object already contains that key from a previous iteration, and if not we add it and assign an empty object to it. Lastly, we assign the old key-value pair inside this newly assigned key so that we can have the nested result we want.

const data = { 
 "AXD:Condor": 12,
 "AXD:Pelican": 20,
 "GPR:Deer": 15,
 "GPR:Owl": 34
}

let res = Object.entries(data).reduce((a, [key, value]) => {
  let outerKey = key.split(':')[0];
  
  if (!a[outerKey]) {
    a[outerKey] = {};
  }
  
  a[outerKey][key] = value;
  return a;
}, {});

console.log(res);

almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error