Converting a JSON string into an ES6 map or another data structure in JavaScript in order to maintain the order of keys

Are there any built-in methods in ES6, JavaScript, or TypeScript to directly convert a JSON string to an ES6 map while preserving the order of keys, or is implementing a custom parser the only option?

Note: I am intentionally avoiding the use of "parse" to prevent converting the JSON string to an object with unordered keys.

For example:

{"b": "bar", "a": "foo" }        // <-- Example JSON string

I would like to achieve:

{ b: "bar", a: "foo" }           // <-- Desired output as a map

Answer №1

UPDATE

https://jsbin.com/kiqeneluzi/1/edit?js,console

In my latest approach, I utilize regex to extract keys from a JSON string while maintaining their order.

let j = "{\"b\": \"bar\", \"a\": \"foo\", \"1\": \"value\"}"
let js = JSON.parse(j)

// Using regex to get keys and maintain the order
let myRegex = /\"([^"]+)":/g;
let keys = []
while ((m = myRegex.exec(j)) !== null) {
    keys.push(m[1])
}

// Transform each key into an object
let res = keys.reduce(function (acc, curr) {
     acc.push({
         [curr]: js[curr]
    });
    return acc
}, []);


console.log(res)

ORIGINAL

If you're looking for an alternative solution for option 2, here's what I have devised.

https://jsbin.com/pocisocoya/1/edit?js,console

let j = "{\"b\": \"bar\", \"a\": \"foo\"}"

let js = JSON.parse(j)

let res = Object.keys(js).reduce(function (acc, curr) {
    acc.push({
      [curr]: js[curr]
    });
    return acc
}, []);


console.log(res)

This method involves retrieving all keys of the object and then applying a reduce function to convert each key into an object.

Answer №2

const convertJsonToMap = (jsonString) => {
    return new Map(JSON.parse(jsonString));
}

For further information, you can visit:

Answer №3

Implementing a for-in loop

let map = new Map();
let jsonObj = {a:'a',b:'b',c:'c'}

for (let i in jsonObj){
map.set(i,jsonObj[i]);
}

On a side note, I came across the comment below and it made me realize that maps are not ordered because they utilize keys rather than indexes to store data.

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

Guidelines on executing a function after page load in meteor

Currently, I am using cursor.observeChanges to monitor new records inserted in MongoDB and trigger a notification when that happens. The issue I am facing is that these notifications are popping up when my app is loaded for the first time or when I navigat ...

jQuery: Performing actions on elements that are both statically included and dynamically generated (using delegated events)

Upon loading the page, I have some "static" HTML tags within a container with the class .file_item and an id of #files_container. Subsequently, new .file_item's are appended (or prepended) to the same container using Ajax without requiring a refresh. ...

AJAX enhancing the functionality of the webgrid with dynamic filtering

I'm encountering a problem with implementing JS on my webgrid for sorting purposes. The scenario is that a user enters a string into a textbox and the webgrid below is refreshed (filtered based on matching results) without the entire page being refres ...

Creating dynamically generated nested text inputs with individual v-model bindings upon the clicking of a button

As a newcomer to vuejs, I am attempting to create nested textboxes dynamically with the click of a button. For a clearer explanation, please refer to this jsfiddle link: https://jsfiddle.net/avi_02/qLqvbjvx/ Let's use an analogy to grasp the iss ...

Tips for concealing material input

In my usual practice, when I need a form field to be part of the submission but not visible, I typically use <input type="hidden" /> However, when working with matInput, the option for a type of hidden is not available. While I could apply display: ...

Error encountered when trying to convert a React Higher Order Component (HOC) to TypeScript: "Exported variable referencing private name"

Seeking assistance from TypeScript experts as I encounter an issue while attempting to convert a React Higher Order Component (HOC) into TS. I'm unsure of how to resolve this. "src/withEnv.tsx(15,14): error TS4025: Exported variable 'withE ...

Tips for Maintaining User Data Across Pages in React using React-Router-Dom and Context

I've been tackling the login functionality of a client-side application. Utilizing React alongside TypeScript, I've incorporated react-router-dom and Context to manage the user's data when they log in. However, upon refreshing the page, the ...

Is it possible to create a personalized serialize form when sending an AJAX POST request

How can I format form data on an AJAX POST request differently than the default $("#formid").serialze()? The current result is not suitable for my needs, as it looks like this: `poststring="csrfmiddlewaretoken=bb9SOkN756QSgTbdJYDTvIz7KYtAdZ4A&colname= ...

Preventing jQuery Validate Plugin from Validating on Blur Events for a Custom Feature

How can I prevent jQuery validate from validating the form on blur events? I have a form with three pairs of start/end dates, each using DatePicker. Each pair should validate if the other field is filled because both are required for form submission. Howe ...

Bringing a JavaScript file into an Ionic/Angular 2 project

I have been attempting to integrate a simple JS library into Angular 2. The library in question is JIC.js. var jic = { /** * This function takes an Image Object (JPG or PNG) and returns a compressed new Image Object * @param {Ima ...

Storing binary data uploaded via AJAX in PHP on the server is essential for maintaining

I successfully imported a .png image file as an Array Buffer. var readSingleFile = function(e) { var file = e.target.files[0]; if (!file) { return; } var reader = new FileReader(); ...

What are the best ways to store internal files in node.js for faster access?

I have been utilizing routing functions like the one mentioned below to replicate the overall design of my website (A.jade): exports.overview = function(req, res, next) { res.render('A', { main: jade.renderFile('./views/B.jade' ...

Is there a way to modify the title of a website upon entering the webpage and then updating it when moving to a new page?

I'm encountering an issue with changing the website title during two specific processes. Upon entering a webpage, the title is modified using the following code: <script type="text/javascript"> $(document).ready(function() { docum ...

Express.js: Request body with an undefined base64 encoding

I'm currently working on transforming a table in .xls format to individual rows in .csv format. I came across a helpful library for this task called XLSX My initial step involves encoding the .xls table into base64 format. Next, I'm attempting ...

Verify if the script has already been loaded. If not, proceed to load it asynchronously

I'm currently working on implementing an asynchronous method to load jQuery JS and then execute callback functions once it is fully loaded. I anticipate using this code repeatedly, so I want to ensure that jQuery (or any other script) is not duplicate ...

Executing specific rendering procedures based on conditions for mapped data - React

When I map data in the returned render, can I then perform a conditional check on that mapped data? export default function App() { const prod = [ {'name': '1'}, {'name': '2'}, {'name': ' ...

A collaborative effort on Facebook, Twitter, and GooglePlus involves generating SCRIPT tags collectively

If you're familiar with the javascripts used by platforms like Facebook, Twitter, and Google Plus, you'll recognize them below. Here, I've simply organized them neatly together. How can I utilize jQuery to create the script tags and optimiz ...

What is the best way to set up TSLint to apply specific rules with one line and different rules with another line

There is a unique method in which I can specify the code to format, such as forcing the else statement to be on the same line as the ending brace of an if statement. "one-line": [ true, "check-open-brace", "check-catch", "check-else", "check-fin ...

Tips for updating a selected value without altering the reference value

Encountering an issue with the angular framework when trying to select a value from ng-for loop <tr *ngFor="let dept of department" (click)="clinicChoose(dept)"> <td class="text-center">{{dept.sectionCode}}</t ...

When invoked by a client-side JS function through XHR, Express fails to render the page in the browser

I'm utilizing Express to pre-process some data from the browser by triggering it through a JS XHR call. However, the issue arises when the browser fails to display the page rendered by Node/Express on the server. This is not a matter of file paths or ...