Home > Article > Web Front-end > nodejs json to array
In the development of Node.js, it is often necessary to operate and parse JSON data. When we parse JSON data into JavaScript objects, sometimes we need to convert it into an array for convenient operation. This article will introduce how to convert JSON data into an array using Node.js.
First, let’s assume we have the following JSON data:
{ "users": [ { "name": "张三", "age": 18 }, { "name": "李四", "age": 22 }, { "name": "王五", "age": 25 } ] }
We can parse it into a JavaScript object using Node.js’ built-in JSON.parse()
method:
const data = '{"users":[{"name":"张三","age":18},{"name":"李四","age":22},{"name":"王五","age":25}]}'; const obj = JSON.parse(data); console.log(obj.users);
The output result is as follows:
[ { name: '张三', age: 18 }, { name: '李四', age: 22 }, { name: '王五', age: 25 } ]
Next, we can use the Array.map()
method to convert the object array into a simple array:
const arr = obj.users.map(user => [user.name, user.age]); console.log(arr);
The output is:
[ [ '张三', 18 ], [ '李四', 22 ], [ '王五', 25 ] ]
If we just want to convert age to an array, we can use the Array.map()
and Array.map()
methods:
const ageArr = obj.users.map(user => user.age); console.log(ageArr);
The output result is:
[ 18, 22, 25 ]
Of course, we can also convert a one-dimensional array into a two-dimensional array. For example, we can use the following code to store the attribute name and attribute value in two arrays:
const keys = Object.keys(obj.users[0]); const values = obj.users.map(user => Object.values(user)); console.log(keys); console.log(values);
The output result is:
[ 'name', 'age' ] [ [ '张三', 18 ], [ '李四', 22 ], [ '王五', 25 ] ]
So far, we have successfully converted the JSON data is an array. It is very convenient to use Node.js to operate JSON data, and various operations can be performed. Hopefully this article helped you better understand how to convert JSON data to array in Node.js.
The above is the detailed content of nodejs json to array. For more information, please follow other related articles on the PHP Chinese website!