Home > Web Front-end > Front-end Q&A > How to convert json string to object in es6

How to convert json string to object in es6

青灯夜游
Release: 2022-10-17 16:32:41
Original
1806 people have browsed it

Conversion steps: 1. Use the JSON.parse() method to convert the json string into an array, the syntax is "JSON.parse(json string)"; 2. Use the expansion operator "..." Just take out the array elements one by one and store them in an empty object "{}", the syntax is "{...array object}".

How to convert json string to object in es6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

JSON

  • JSON is a special string format, essentially a string

  • Like objects and arrays, if the key and value inside are in string format, they are wrapped in double quotes (must be double quotes)

Example:

var jsonStr = '{ "name": "cxh", "sex": "man" }';
Copy after login

How to convert json string to object in es6

es6 method of converting a json string into an object

In es6, you can use arrays and use JSON.parse( ) method and the spread operator "..." to convert json strings into objects.

Conversion steps:

Step 1. Use the JSON.parse() method to convert the json string into an array

JSON.parse() method converts data into JavaScript objects

var jsonStr = '[1,2,3,{"a":1}]';
var arr=JSON.parse(jsonStr);
console.log(arr);
Copy after login

How to convert json string to object in es6

Step 2: Use the spread operator "..." Convert an array into an object

The spread operator "..." can expand the array, take out the array elements one by one, and then store them in an empty object "{}".

const obj = {...arr} ;
console.log(obj);
Copy after login

How to convert json string to object in es6

[Related recommendations: javascript video tutorial, programming video

The above is the detailed content of How to convert json string to object in es6. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template