Guide on converting a unique JSON structure into a JavaScript object

I've been on the hunt for a solution to this unique format challenge, but have hit a dead end so far.

The issue at hand is that I'm dealing with a JSON format that doesn't play nicely with mongoDB. My goal is to convert the JSON data into a standard JavaScript object. However, with over 2,000 entries to handle, manual manipulation is out of the question. Plus, I couldn't get JSON.parse(data) to work for this particular format.

Here's an example of the current JSON structure:

{
    "一": {
        "strokes": 1,
        "grade": 1,
        "freq": 2,
        "jlpt_old": 4,
        "jlpt_new": 5,
        "meanings": ["One","One Radical (no.1)"],
        "readings_on": ["いち","いつ"],
        "readings_kun": ["ひと-","ひと.つ"],
        "wk_level": 1,
        "wk_meanings": ["One"],
        "wk_readings_on": ["いち","いつ"],
        "wk_readings_kun": ["!ひと"],
        "wk_radicals": ["Ground"]
    },
    "二": {
        "strokes": 2,
        "grade": 1,
        "freq": 9,
        "jlpt_old": 4,
        "jlpt_new": 5,
        "meanings": ["Two","Two Radical (no. 7)"],
        "readings_on": ["に","じ"],
        "readings_kun": ["ふた","ふた.つ","ふたたび"],
        "wk_level": 1,
        "wk_meanings": ["Two"],
        "wk_readings_on": ["に"],
        "wk_readings_kun": ["!ふた"],
        "wk_radicals": ["Two"]
    },
}

And here is the desired format I aim to achieve:

[
    {
        kanji: "一",
        strokes: 1,
        grade: 1,
        freq: 2,
        jlpt_old: 4,
        jlpt_new: 5,
        meanings: ["One","One Radical (no.1)"],
        readings_on: ["いち","いつ"],
        readings_kun: ["ひと-","ひと.つ"],
        wk_level: 1,
        wk_meanings: ["One"],
        wk_readings_on: ["いち","いつ"],
        wk_readings_kun: ["!ひと"],
        wk_radicals: ["Ground"]
    },
    {
        kanji: "二",
        strokes: 2,
        grade: 1,
        freq: 9,
        jlpt_old: 4,
        jlpt_new: 5,
        meanings: ["Two","Two Radical (no. 7)"],
        readings_on: ["に","じ"],
        readings_kun: ["ふた","ふた.つ","ふたたび"],
        wk_level: 1,
        wk_meanings: ["Two"],
        wk_readings_on: ["に"],
        wk_readings_kun: ["!ふた"],
        wk_radicals: ["Two"]
    }
]

As shown, the original format uses keys to describe each object, while the desired format nests all details within the object itself.

If anyone could provide some insight or assistance on tackling this challenge, it would be greatly appreciated! :)

Answer №1

Both examples represent valid JSON objects, showcasing a simple manipulation:

const data = {
    "一": {
        "strokes": 1,
        "grade": 1,
        "freq": 2,
        "jlpt_old": 4,
        "jlpt_new": 5,
        "meanings": ["One","One Radical (no.1)"],
        "readings_on": ["いち","いつ"],
        "readings_kun": ["ひと-","ひと.つ"],
        "wk_level": 1,
        "wk_meanings": ["One"],
        "wk_readings_on": ["いち","いつ"],
        "wk_readings_kun": ["!ひと"],
        "wk_radicals": ["Ground"]
    },
    "二": {
        "strokes": 2,
        "grade": 1,
        "freq": 9,
        "jlpt_old": 4,
        "jlpt_new": 5,
        "meanings": ["Two","Two Radical (no. 7)"],
        "readings_on": ["に","じ"],
        "readings_kun": ["ふた","ふた.つ","ふたたび"],
        "wk_level": 1,
        "wk_meanings": ["Two"],
        "wk_readings_on": ["に"],
        "wk_readings_kun": ["!ふた"],
        "wk_radicals": ["Two"]
    }
};

const parsed = Object.entries(data).reduce((acc, [kanji, obj]) => acc.concat({kanji, ...obj}), []);
console.log(parsed)

Answer №2

All you need is a single map() call on the parsed JSON's Object.entries().

const json = '{"one":{"strokes":1,"grade":1,"freq":2,"jlpt_old":4,"jlpt_new":5,"meanings":["One","One Radical (no.1)"],"readings_on":["いち","いつ"],"readings_kun":["ひと-","ひと.つ"],"wk_level":1,"wk_meanings":["One"],"wk_readings_on":["いち","いつ"],"wk_readings_kun":["!ひと"],"wk_radicals":["Ground"]},"two":{"strokes":2,"grade":1,"freq":9,"jlpt_old":4,"jlpt_new":5,"meanings":["Two","Two Radical (no. 7)"],"readings_on":["に","じ"],"readings_kun":["ふた","ふた.つ","ふたたび"],"wk_level":1,"wk_meanings":["Two"],"wk_readings_on":["に"],"wk_readings_kun":["!ふた"],"wk_radicals":["Two"]}}';

const obj = JSON.parse(json);

const refactored = Object.entries(obj).map(([k, v]) => ({kanji: k, ...v}));

console.log(refactored);

Answer №3

Is this suitable for you?

let database = {
    "一": {
        "strokes": 1,
        "grade": 1,
        "freq": 2,
        "jlpt_old": 4,
        "jlpt_new": 5,
        "meanings": ["One","One Radical (no.1)"],
        "readings_on": ["いち","いつ"],
        "readings_kun": ["ひと-","ひと.つ"],
        "wk_level": 1,
        "wk_meanings": ["One"],
        "wk_readings_on": ["いち","いつ"],
        "wk_readings_kun": ["!ひと"],
        "wk_radicals": ["Ground"]
    },
    "二": {
        "strokes": 2,
        "grade": 1,
        "freq": 9,
        "jlpt_old": 4,
        "jlpt_new": 5,
        "meanings": ["Two","Two Radical (no. 7)"],
        "readings_on": ["に","じ"],
        "readings_kun": ["ふた","ふた.つ","ふたたび"],
        "wk_level": 1,
        "wk_meanings": ["Two"],
        "wk_readings_on": ["に"],
        "wk_readings_kun": ["!ふた"],
        "wk_radicals": ["Two"]
    },
}

let result = [];
for(let key in database){
   result.push({ kanji: key, ...database[key]});
}
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

Retrieving data from the array properties in a JSON object

I am facing a challenge with an array of elements, each element is quite complex as it contains nested arrays as properties. My goal is to extract specific attributes from these elements, but I have been struggling to achieve this using the forEach functio ...

Issues with parsing JSON data within PowerShell

While working with JSON, I encountered a specific issue that I need help with. The JSON snippet provided below illustrates the problem: Although I have experimented with various examples of JSON manipulation, most of them focus on simple key/value pairs. ...

Developing dynamic 3D cubes

In my latest project, I am attempting to construct a unique structure composed of 3D cubes arranged in a stacked formation. Each of the individual cubes within this structure is designed to be interactive for users. When a user hovers over a cube, it trigg ...

Display personalized error messages using jQuery and PHP

I implemented an Ajax autocomplete feature on an input field within a form using jQuery. Here are the ajax settings I have set up: $.ajax({ type: "POST", url: myUrl, data: $("#id__form").serialize(), success: function(data){ ...

Exploring Array Iteration and Incrementing with Easing Techniques

I am currently working on a function that involves iterating over an array and incrementing the values by varying amounts. The challenge is to decrease these incremental amounts as the values in the array get larger. Let's consider the following exam ...

Is there a way to circumvent the eg header along with its contents and HTML code using JavaScript?

I have a script in JavaScript that is designed to replace the content of data-src attribute within each img tag with src. However, I am facing an issue where this script interferes with the functionality of a slider located in the header section. The sli ...

Is Angular 2 Really Suitable for Multi-Page Applications?

I am currently working on a multi-page app using Angular2 and have noticed that the load times are slower than desired when in development mode. While searching for solutions, I came across a thread on stackoverflow that explains how to set up Angular2 fo ...

Utilizing Jersey Rest Webservices and Java to Extract Data from JSON Arrays

Receiving a JSON array from an iOS client and aiming to parse it on the server side using Java, Jersey, and Gson. The JSON array is sent via POST method from iOS. The hurdle lies in figuring out how to save the JSON data into a Java class. Shown below is t ...

Convert your AS3 code to JavaScript with our specialized compilers

Recently, I came across the AS3 to JS compiler known as Jangaroo. It caught my attention because it seems like a valuable tool that aligns well with my preferences in AS3. Are there any similar compilers out there? Is there another programming language ...

Cannot display data in template

After successfully retrieving JSON data, I am facing trouble displaying the value in my template. It seems that something went wrong with the way I am trying to output it compared to others. My function looks like this, getUserInfo() { var service ...

The lookat() function in three.js isn't functioning according to my requirements

Here is the code snippet I am working with: http://codepen.io/usf/pen/pGscf This is the specific section of interest: function animate() { //sun.rotation.x = t/1000; sun.rotation.y += 0.01; t += 0.1; earth.position.x = Math.sin((2*Ma ...

The issue of ColdFusion JSON not being handled by JQuery

I am working on a straightforward ColdFusion component that interacts with a database and returns a JSON object <cfcomponent> <cfsetting showdebugoutput="false" enablecfoutputonly="true"> <cffunction name="getNew" access="remote" returntype ...

Guide to retrieve MongoDB documents with BigDecimal values higher than a specified threshold in Java

The issue I'm encountering is that I can't retrieve MongoDB records with an amount (represented as a Bigdecimal value) greater than zero when using the following code in Java. Query query=new Query(); query.addCriteria(Criteria.where(&quo ...

What is the best way to retrieve unique column values using the LoopBack REST API?

I am working with a loopback REST API that fetches data from a MySQL table and returns it in JSON format. However, I need to apply a filter or query so that only distinct values for a specific column are returned. In SQL, we use the syntax SELECT DISTINC ...

using reactjs to dynamically render elements based on the selected condition in a select box

Is there a way to dynamically change an element based on the selected value of a dropdown in React? I'm looking for help with rendering conditions. Here's a snippet of my code: <Col span={12}> <Form.Item label='Qu ...

Angular's mat table paginator now efficiently loads all data directly onto the first page

Currently, I am facing an issue while loading JSON data from a backend ASP.NET Core C# API to an Angular material table. The problem lies in the fact that all 100 rows of JSON data are being loaded onto the first page, despite setting up the paginator with ...

Is the Utilization of Inline JavaScript in HTML Attributes by Angular considered a "good practice"?

While going through the Angular tutorials, I found a lot to like. However, I couldn't help but wonder if "ng-click" is not essentially just an inline onClick function. My understanding was that the JavaScript community frowned upon using inline JavaSc ...

Encountering an issue while trying to import the instanceMethods function within Sequelize

In a file, I have written a function and exported it like this: export function foo(params...) { // do something } When initializing the model, I imported the function in the following manner: import { foo } from "../path/..." instanceMethods: { foo ...

Node.Js Web Scraping: How to Extract Data from JavaScript-Rendered Pages Using Request

I am looking to extract specific content from Google search results that is only visible in browsers, potentially due to Javascript being enabled. Specifically, I am interested in scraping the Knowledge Graph "People also search for" information. Currentl ...

NodeJs google analytics reporting API returning null response object

Just getting started with a question. In my project, I am utilizing NodeJS to interact with the Google Analytics Reporting API. I have successfully obtained the necessary OAuth 2 token and even receive a 200 response when querying the API. However, instea ...