nodejs json to array

WBOY
Release: 2023-05-28 09:48:37
Original
758 people have browsed it

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
    }
  ]
}
Copy after login

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);
Copy after login

The output result is as follows:

[
  { name: '张三', age: 18 },
  { name: '李四', age: 22 },
  { name: '王五', age: 25 }
]
Copy after login

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);
Copy after login

The output is:

[
  [ '张三', 18 ],
  [ '李四', 22 ],
  [ '王五', 25 ]
]
Copy after login

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);
Copy after login

The output result is:

[ 18, 22, 25 ]
Copy after login

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);
Copy after login

The output result is:

[ 'name', 'age' ]
[
  [ '张三', 18 ],
  [ '李四', 22 ],
  [ '王五', 25 ]
]
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!