transforming json data into an array or map

Once my REST API responds, it provides the following JSON content:

[{
    "key": "apple",
    "value": "green"
},
{
    "key": "banana",
    "value": "yellow"
}]

Managing the data, I use the following code to iterate through the list:

this.props.json.map(row => {
    return <RowRender key={id.row} row={row} />
}

While the content displays correctly, an error appears in the web browser console:

map is not a function

To address this, I searched online and altered my code as follows:

Array.prototype.slice.call(this.props.json).map(row => {
    return <RowRender key={id.row} row={row} />
}

Although this resolves the error, the solution appears complicated. Is this the correct approach for this task?


UPDATE

My attempts so far:

  • Using JSON.parse(...).map: I encounter an "Unexpected end of JSON input" error
  • Using JSON.parse(JSON.stringify(...)).map(...): The data displays but I receive an error: "JSON.parse(...).map is not a function"
  • Using Array(...).map: I face the issue that each child in array or iterator should have a unique key.

Answer №1

To easily access both keys and values from an object, use Object.entries(). Then, you can pass this to Map() to retrieve values based on keys.

Create a new Map object by passing Object.entries(this.props.json) as shown below:
let myMap = new Map(Object.entries(this.props.json));

Answer №2

When looking at your code, it appears that this.props.json is not technically an array, but rather an object that behaves like an array. The issue lies in trying to use a function like map, which is specifically for arrays. To fix this issue, you are correctly converting the array-like object into an actual array using .slice()

For a more elegant solution, you can use the following approach:

Array.from(this.props.json).map(item => <ItemComponent key={item.id} data={item} />)

Answer №3

You can easily achieve this as mentioned by @Gary in his response:

Moving from Map to JSON with string keys:

const personsJson = `{"1":{"firstName":"Jan","lastName":"Kowalski"},"2":{"firstName":"Justyna","lastName":"Kowalczyk"}}`;
const personsObject = JSON.parse(personsJson);
const personsMap = new Map(Object.entries(personsObject));
for (const key of personsMap.keys()) {
    console.log(typeof key)
}

However, it is important to note an issue that requires attention. When creating a map in this manner, the keys will always be STRING. This is because the key of a JSON object is always a STRING. If your map keys should be numbers, you will need to parse the keys of your object entries first.

  • Converting from JSON to Map with number keys::

const personsJson = `{"1":{"firstName":"Jan","lastName":"Kowalski"},"2":{"firstName":"Justyna","lastName":"Kowalczyk"}}`;
const personsObject = JSON.parse(personsJson);
const personObjectEntries = Object.entries(personsObject);
const personObjectEntriesNumberKeys = personObjectEntries.map(person => {
    person[0] = parseInt(person[0]);
    return person;
});
const personsMap = new Map(personObjectEntriesNumberKeys);
for (const key of personsMap.keys()) {
    console.log(typeof key)
}

The use of person[0] is necessary because the key of the object is located at index 0

Answer №4

const mapToArray = JSON.stringify([...userMap.entries()]);
const newUserMap = new Map(JSON.parse(mapToArray));

Answer №5

Feel free to use this handy function for converting JSON into a Map of Maps:

This function is designed to work with JSON data structured like the example below:

{
   "data":{
      "1":{
         "color":"red",
         "size":"big"
      },
      "2":{
         "color":"red",
         "size":"big"
      },
      "3":{
         "color":"red",
         "size":"big"
      },
      "4":{
         "color":"red",
         "size":"big"
      },
      "5":{
         "color":"red",
         "size":"big"
      }
   }
}
function jsonToMap(jsonString)  {
    var jsonObject = JSON.parse(jsonString);
    var dataObject = jsonObject.data;
    var dataMap = new Map(Object.entries(dataObject));
    var resultMap = new Map();
    for (const key of dataMap.keys())  {
        console.log(key);
        var keyMap = new Map(Object.entries(dataMap.get(key)));
        resultMap.set(key, keyMap);
    }

    console.log("done!");
    return resultMap;
}

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

Issue with the react-redux Provider

Whenever I run my basic program Index.js function test(state = []) { return state } const store = createStore(test); render( <Provider store = { store } > <App / > < /Provider > , document.getElementById('root') ...

405 - Sorry, this method is not allowed for deletion

The issue at hand involves a Spring RESTful web service and a client. When attempting a DELETE request on the server, the following error is encountered: -> DELETE http://localhost:8080/employee/3/logout 405 (Method Not Allowed) Despite implementing th ...

Utilize JQuery to extract data from JSON and populate form inputs

Working on a web project where I need to make use of AJAX and JQuery to update certain fields without refreshing the entire page. After testing, everything seemed to work fine with dummy data. However, when trying to parse actual JSON data generated from M ...

Move the cursor over the text to reveal an image

Hello, I'm trying to replicate the same animation effect as seen on these websites: and . Specifically, when hovering over the "selected works" section, an image is displayed. I suspect it's using a JavaScript library, but I can't seem to i ...

Unusual actions when making a $.ajax call using the PUT method

When making a call to $.ajax, I use the following code: $.ajax({ type: 'PUT', url: model.url(), data: {task: {assigned_to: selected()}}, contentType: 'application/json' }) The function selected() returns an array. However, th ...

Reveal each element individually upon clicking the button

I am trying to display 5 div elements one by one when clicking a button, but the current code is not working. I am open to alternative solutions for achieving this. Additionally, I want to change the display property from none to flex in my div element. ...

Enforce numerical input in input field by implementing a custom validator in Angular 2

After extensive research, I was unable to find a satisfactory solution to my query. Despite browsing through various Stack Overflow questions, none of them had an accepted answer. The desired functionality for the custom validator is to restrict input to ...

What exactly is the concept of lazily installing a dependency?

The website here contains information about the changes in Ember 2.11. Ember 2.11 now utilizes the ember-source module instead of the ember Bower package. In the upcoming Ember CLI 2.12 release, Bower will no longer be installed by default but will only ...

What could be the reason behind the login button not triggering the console message display?

I've decided to delve into web server development on my own and have been tweaking a GitHub repository for ExpressJS with Typescript that I stumbled upon. My initial goal is simple - just to have something displayed on the console when I click the log ...

Place a list with scrolling and overflow features side by side

Having trouble getting my headers to scroll with overflow auto and white-space nowrap. Can't figure out why it's not working. I want to create hyperlinks within headers to link to specific parts of the website. I have the code for hyperlinking s ...

Having issues with NextJs app router and redux-toolkit not resetting to initial state after server-side rendering (SSR)

I am facing a challenge in my NextJs project with the app router and redux/toolkit for state management. When navigating from one page to another, the data fetched on the previous page remains in the redux state even though it wasn't fetched on the cu ...

When using Ionic, clicking on a Google Maps marker to navigate to another page with NavController can sometimes result in the clicks on the new

Upon successfully displaying the pushed page, I encountered a strange issue where all elements with a (click)='doSomething()' binding stopped working throughout the newly loaded page. Additionally, there was an ion-slides element on the pushed pa ...

Conversion of CSV data into JSON format parameter

I'm currently working on converting a CSV file to a JSON file. library(readr) data <- read_csv("6_items.csv") json_data <- toJSON(data, pretty=TRUE) View(json_data) write_json(json_data, "6_items.json" ) https://i.sstatic.n ...

Guide to Subscribing to a nested observable with mergeMap within a button's click event

The issue arises in the "addToWishlist" function as I attempt to concatenate the result of the outer observable with the inner observable array and then call the next method on the inner observable. The "addToWishlist" method is triggered by the click ha ...

Addressing the delay of "Rasterize Paint" on mobile devices while implementing css3 opacity transitions

I'm currently working on a project that involves users navigating back and forth between modals. To achieve this, I decided to use CSS transitions to change the opacity from 0 to 1. However, I've encountered some issues with slow transitions. So ...

The feature 'forEach' is not available for the 'void' type

The following code is performing the following tasks: 1. Reading a folder, 2. Merging and auto-cropping images, and 3. Saving the final images into PNG files. const filenames = fs.readdirSync('./in').map(filename => { return path.parse(filen ...

What is the most effective way to output data using the response.write method in a Node.js program after retrieving it from a MySQL server?

Currently working on a NodeJS web app and encountering a roadblock. Seeking feedback on my code: var config = require('./config.json'); var mysql = require('mysql'); var http = require('http'); var url = require('url&apo ...

Prevent further execution upon callback in an AJAX request by stopping the click event function

When the function myClick() is called within itself instead of myLoad() on the first click, it leads to double execution of myClick() on the second click. => This results in two consecutive executions of the click event for #myBtn with just one click. ...

Ways to activate paging feature in the Extension JS Basic Grid

I am currently working with an Extension Js grid and using Json to bind the data. I am trying to enable paging in the grid with a page size of '10', but unfortunately, my paging functionality is not working as expected. Below is the code snippet ...

Leveraging the power of Google Closure Templates alongside the versatility of

We are embarking on developing an application using JavaScript and HTML5 that will utilize a rest API to access server resources, leveraging the power and convenience of jQuery which our development team is already proficient in. Our goal is to make this a ...