Transform nested JSON objects into a JSON array using JavaScript

Hey there! I've got this JSON structure that I'm trying to convert into an array without having to iterate over each element. Is there a JavaScript function that can help me achieve this?

{
  "ES": {
    "130": {
      "code": "A Coruсa",
      "name": "A Coruña"
    },
    "131": {
      "code": "Alava",
      "name": "Alava"
    },
    "...": {
      "code": "...",
      "name": "..."
    }
  },
  "CH": {
    "104": {
      "code": "AG",
      "name": "Aargau"
    },
    "...": {
      "code": "...",
      "name": "..."
    }
  },
  "...": {
    "...": {
      "code": "...",
      "name": "..."
    }
  }
}

Here's the desired output:

[
    {
      "code": "A Coruсa",
      "name": "A Coruña"
    },
    {
      "code": "Alava",
      "name": "Alava"
    },
    {
      "code": "...",
      "name": "..."
    },
    {
      "code": "AG",
      "name": "Aargau"
    },
    {
      "code": "...",
      "name": "..."
    },
    {
      "code": "...",
      "name": "..."
    }
]

Appreciate any recommendations or help you can provide. Thank you!

Answer №1

One way to iterate over properties and assemble an array is by using Object.keys(), Array.prototype.reduce(), and Array.prototype.map().

var obj = { "ES": { "130": { "code": "A Coruсa", "name": "A Coruña" }, "131": { "code": "Alava", "name": "Alava" }, }, "CH": { "104": { "code": "AG", "name": "Aargau" } } },
    result = Object.keys(obj).reduce(function (r, k) {
        return r.concat(Object.keys(obj[k]).map(function (kk) {
            return obj[k][kk];
        }));
    }, []);

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

Answer №2

Check out this fiddle I made for data conversion:

https://jsbin.com/suzice/edit?js,output

  var newData = {
  "ES": {
    "130": {
      "code": "A Coruña",
      "name": "A Coruña"
    },
    "131": {
      "code": "Alava",
      "name": "Alava"
    },
    "...": {
      "code": "...",
      "name": "..."
    }
  },
  "CH": {
    "104": {
      "code": "AG",
      "name": "Aargau"
    },
    "...": {
      "code": "...",
      "name": "..."
    }
  }
};
var dataList = [];
Object.keys(newData).forEach(function(mainKey){

  Object.keys(newData[mainKey]).forEach(function(subKey){
     dataList.push(newData[mainKey][subKey]);
  });
  console.log(dataList);

});

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

Is there a way to utilize javascript std input/output in repl.it effectively?

I created a straightforward program that calculates the factorial of a specified number, and I am interested in running it on repl.it. During its execution, I would like to interact with standard input and output through the command line. Is there a way ...

How can I fetch and reference multiple local JSON files in Vue using Axios?

I am currently utilizing vue for prototyping some HTML components. Is there a method to make Vue detect two separate JSON files? vue.js var vm = new Vue({ el: '#douglas-laing', data: { products: [], contentPanels: [] }, created() ...

No need for jQuery with this scrolling image gallery

I recently created a horizontal scrolling image gallery with thumbnails underneath. The goal is to click on a thumbnail and have the corresponding image scroll into view. Here's the HTML setup: <div class="images_container"> <img id="imag ...

Connecting to the Wordpress server using RestKit

Trying to send a JSON to a local Wordpress server, with the following mapping: [RKMIMETypeSerialization registerClass:[RKNSJSONSerialization class] forMIMEType:@"text/html"]; RKObjectMapping *orderEntryMapping = [RKObjectMapping requestMapping]; [orderE ...

Learning how to implement server side rendering in React JS through tutorials

After diving into the world of React js and mastering the basics, I successfully created web pages using this technology. I also honed my skills with node js and express. However, now I am faced with a new challenge: server side rendering. The tutorials av ...

Navigating with VueRouter in your Chrome Extension is a breeze

I have been working on a Chrome extension using Vue 3 + VueRouter. One issue I encountered was trying to change the router-view content to display a different component, essentially showing users a different UI. Despite my efforts and various methods use ...

Creating specific CSS classes for individual slides in a basic slider framework

So, I have a rather simple slider that is created using only CSS. Each slide has unique labels for navigation buttons. The main question here is: how can I dynamically add or remove classes to specific items on the slide only when that particular slide is ...

Issue with Android app: Incorrect information is shown in the toast notification when clicking on a list view item

Whenever I click on a specific id, it displays data from another id. Please review the code below to understand my issue. What is wrong with this code? It seems like I'm not storing any position in it. If that's the only problem, please provide ...

Reload the MEN stack webpage without the need to reload the entire page

I am in the process of developing a data analytics dashboard using the MEN stack (MongoDB, Express.js, Node.js). I have successfully implemented functionality to display real-time data that refreshes every 5 seconds without the need to reload the entire ...

What is the correct way to position a material-ui icon within a button for proper alignment?

Is there a way to properly align the <ChevronRightIcon> within the <PrimaryButton>? I want it to appear after the button label on the right side. https://i.stack.imgur.com/dcEWo.png <PrimaryButton style={{ paddingRight: &apo ...

Arranging DIVs in a vertical layout

Currently, I am working on a design that involves organizing several <DIV> elements in a vertical manner while still maintaining responsiveness. Here are some examples: Wider layout Taller layout I have tried using floats, inline-block display, ...

collecting user input in React.js

After doing some research on React.js from this website, I stumbled upon a piece of code that left me puzzled. As far as I can tell, the checkbox for isGoing will be pre-filled as true (checked) and the numberOfGuests will be set to 2. However, I found m ...

Combining react-draggable and material-ui animations through react-transition group: a comprehensive guide

Trying to incorporate react-draggable with material-UI animations. One approach is as follows: <Draggable> <Grow in={checked}> <Card className={clsx(classes.abs, classes.paper)}> <svg classN ...

The variable _spPageContextInfo has not been defined, resulting in a ReferenceError

The code in my JavaScript file looks like this: var configNews = { url:_spPageContextInfo.webAbsoluteUrl, newsLibrary: 'DEMONews', listId: '' }; // Attempting to retrieve the List ID $.ajax({ url: configNews.url + "/_a ...

Error message: React Native encountered a prop type failure when an invalid prop of type array was passed to the Overlay component

I am brand new to React Native and encountering an error message when opening a specific component. Although it doesn't hinder navigation, I would like to resolve this issue. I suspect it could be related to a syntax or typo error, but pinpointing the ...

Finding the position of the biggest floating point number in the array

What is the best way to find the index of the largest element in an array of floating point numbers? [0.000004619778924223204, 0.8323721355744392, 0.9573732678543363, 1.2476616422122455e-14, 2.846605856163335e-8] Once the index of the largest element is ...

Storing multiple values of dynamically added elements in a single variable and accessing them within a function

Is it possible to store multiple values into a single variable and then access them in a setTimeout function? $(document).ready(function (){ div ({'div':'#noo','auto':'true','pos':'top',' ...

How to nullify the valueChanges pipe in Angular RxJS until the observable is resolved

A challenge I am facing is piping the valueChanges from a select element to trigger the appropriate API request and displaying a spinner until the response is received. Additionally, I am trying to utilize publish() and refCount() methods so that I can use ...

Tips for customizing the appearance of the day button in a React Material-UI date picker

In my React project, I am using material-ui date picker and I am looking for a way to customize the styling of the day buttons. Specifically, I want to change the text color of the available days. By default, as seen in the screenshot, the text color is bl ...

Vue.js has encountered a situation where the maximum call stack size has been exceeded

I have implemented a method called cartTotal that calculates the total price of my products along with any discounts applied, and I am trying to obtain the final value by subtracting the discount from the total. cartTotal() { var total = 0; var di ...