Home  >  Article  >  Web Front-end  >  nodejs json to array

nodejs json to array

WBOY
WBOYOriginal
2023-05-28 09:48:37784browse

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!

Statement:
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
Previous article:nodejs database to jsonNext article:nodejs database to json