Home Web Front-end JS Tutorial How to optimize JSON data grouping in JS

How to optimize JSON data grouping in JS

Apr 14, 2018 am 10:14 AM
javascript json optimization

This time I will bring you how to optimize the JSON data grouping of JS, JS JSON data grouping optimizationWhat are the precautions?The following is a practical case, let's take a look.

There is a bunch of data that I need to group by time for the front-end view to render

[
 {"date":"2017-12-22","start_time":"10:00:00","end_time":"10:00:00","status":"Performance Time"},
 {"date":"2017-12-22","start_time":"10:40:00","end_time":"10:40:00","status":"Performance Time"},
 {"date":"2017-12-23","start_time":"10:00:00","end_time":"10:00:00","status":"Performance Time"},
 {"date":"2017-12-23","start_time":"10:40:00","end_time":"10:40:00","status":"Performance Time"}
]
Copy after login

It needs to be converted into the following

[
 {
 date: '2017-12-22',
 data: [
  {
  date: '2017-12-22',
  start_time: '10:00:00',
  end_time: '10:00:00',
  status: 'Performance Time'
  },
  {
  date: '2017-12-22',
  start_time: '10:40:00',
  end_time: '10:40:00',
  status: 'Performance Time'
  }
 ]
 },
 {
 date: '2017-12-23',
 data: [
  {
  date: '2017-12-23',
  start_time: '10:00:00',
  end_time: '10:00:00',
  status: 'Performance Time'
  },
  {
  date: '2017-12-23',
  start_time: '10:40:00',
  end_time: '10:40:00',
  status: 'Performance Time'
  }
 ]
 }
]
Copy after login

1. Original method, a lot of networks

var map = {},
 nList = []
 //遍历原始数组
 for (var i = 0; i < arr.length; i++) {
 var item = arr[i]
 //如果map没有则在新nList中添加
 if (!map[item.date]) {
  nList.push({
  date: item.date,
  data: [item]
  })
  map[item.date] = item
 } else {
  //遍历nList
  for (var j = 0; j < nList.length; j++) {
  var nItem = nList[j]、
  //如查找到date符合则添加
  if (nItem.date == item.date) {
   nItem.data.push(item)
   //跳出循环
   break
  }
  }
 }
 }
Copy after login

Running efficiency: It takes about 3ms to traverse 1000 times. I always felt that it was not elegant, and the features of ES5 were not used, so I decided to optimize it myself!

2. Use ES5 features

Replace for with forEach and every

let map = {},
 nList = []
 arr.forEach((item) => {
 if (!map[item.date]) {
  nList.push({
  date: item.date,
  data: [item]
  })
  map[item.date] = item
 } else {
  //因为forEach不支持break,所以使用every实现
  nList.every((nItem) => {
  if (nItem.date === item.date) {
   nItem.data.push(item)
   return false
  }
  return true
  })
 }
 })
Copy after login

Performance Optimization50%, about 1.5ms!

3. Performance optimization practice

Because the dates in my array are arranged in order and there are no duplicates, I can consider removing the second loop

let map = {},
 nList = []
 //设置初始key为0
 let _nkey = 0
 arr.forEach((item, index) => {
 if (index === 0) {
  nList.push({
  date: item.date,
  data: [item]
  })
 } else {
  let oItem = arr[index - 1]
  //和前一个date一致则在当前添加,否则添加至nList
  if (item.date === oItem.date) {
  nList[_nkey]['data'].push(item)
  } else {
  nList.push({
   date: item.date,
   data: [item]
  })
  _nkey ++
  }
 }
 })
Copy after login

The efficiency is optimized again by 50%, about 1ms!

PS: JS operation JSON summary

JSON(JavaScript Object Notation) It is a lightweight data exchange format that uses a completely language-independent text format and is an ideal data exchange format. At the same time, JSON is a JavaScript native format, which means that in Processing JSON data in JavaScript does not require any special API or toolkit.

This article mainly summarizes the essentials of JS operating JSON.

In JSON, there are two structures: Object and array.

1. An object starts with "{" (left bracket) and ends with "}" (right bracket). Each "name" is followed by a ":" (colon); "name/value" pairs are separated by "," (comma). The name is enclosed in quotation marks; if the value is a string, it must be enclosed in parentheses, and if it is a numeric value, it is not necessary. For example:

var o={"xlid":"cxh","xldigitid":123456,"topscore":2000,"topplaytime":"2009-08-20"};
Copy after login

2. An array is an ordered collection of values. An array starts with "[" (left bracket) and ends with "]" (right bracket). Use "," (comma) to separate values.

For example:

  var jsonranklist=[{"xlid":"cxh","xldigitid":123456,"topscore":2000,"topplaytime":"2009-08-20"},{"xlid":"zd","xldigitid":123456,"topscore":1500,"topplaytime":"2009-11-20"}];
Copy after login

In order to process JSON data conveniently, JSON provides the json.js package, download address: http://www.json.org/json.js

In the data transmission process, json is transmitted in the form of text, that is, a string, and JS operates on JSON objects, so the mutual conversion between JSON objects and JSON strings is the key. For example:

JSON string:

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

JSON object:

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

1. Convert JSON string to JSON object

To use the above str1, you must use the following to convert it into a JSON object first:

  //由JSON字符串转换为JSON对象
var obj = eval('(' + str + ')');
Copy after login

Or

var obj = str.parseJSON(); //由JSON字符串转换为JSON对象
Copy after login

Or

  var obj = JSON.parse(str); //由JSON字符串转换为JSON对象
Copy after login

Then, you can read it like this:

  Alert(obj.name);
  Alert(obj.sex);
Copy after login

Special note: If obj is originally a JSON object, it will still be a JSON object after conversion using the eval() function (even if it is converted multiple times), but there will be questions after processing using the parseJSON() function (throwing a syntax exception).

2. You can use toJSONString() or the global method JSON.stringify() to convert the JSON object into a JSON string.

For example:

var last=obj.toJSONString(); //将JSON对象转化为JSON字符
Copy after login

Or

  var last=JSON.stringify(obj); //将JSON对象转化为JSON字符
  alert(last);
Copy after login

Attention:

Among the above methods, except that the eval() function comes with js, many other methods come from the json.js package. New version of JSON modified API, both JSON.stringify() and JSON.parse() methods are injected into the built-in object of Javascript, and the former becomes Object.toJSONString(), which becomes String.parseJSON(). If you are prompted that the toJSONString() and parseJSON() methods cannot be found, it means that your json package version is too low.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the use of JS's multi-threaded runtime library Nexus.js

How to operate jackson when parsing a json string Letter case conversion


#

The above is the detailed content of How to optimize JSON data grouping in JS. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Performance optimization tips for converting PHP arrays to JSON Performance optimization tips for converting PHP arrays to JSON May 04, 2024 pm 06:15 PM

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

C++ program optimization: time complexity reduction techniques C++ program optimization: time complexity reduction techniques Jun 01, 2024 am 11:19 AM

Time complexity measures the execution time of an algorithm relative to the size of the input. Tips for reducing the time complexity of C++ programs include: choosing appropriate containers (such as vector, list) to optimize data storage and management. Utilize efficient algorithms such as quick sort to reduce computation time. Eliminate multiple operations to reduce double counting. Use conditional branches to avoid unnecessary calculations. Optimize linear search by using faster algorithms such as binary search.

How to optimize the startup items of WIN7 system How to optimize the startup items of WIN7 system Mar 26, 2024 pm 06:20 PM

1. Press the key combination (win key + R) on the desktop to open the run window, then enter [regedit] and press Enter to confirm. 2. After opening the Registry Editor, we click to expand [HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionExplorer], and then see if there is a Serialize item in the directory. If not, we can right-click Explorer, create a new item, and name it Serialize. 3. Then click Serialize, then right-click the blank space in the right pane, create a new DWORD (32) bit value, and name it Star

Quick tips for converting PHP arrays to JSON Quick tips for converting PHP arrays to JSON May 03, 2024 pm 06:33 PM

PHP arrays can be converted to JSON strings through the json_encode() function (for example: $json=json_encode($array);), and conversely, the json_decode() function can be used to convert from JSON to arrays ($array=json_decode($json);) . Other tips include avoiding deep conversions, specifying custom options, and using third-party libraries.

Vivox100s parameter configuration revealed: How to optimize processor performance? Vivox100s parameter configuration revealed: How to optimize processor performance? Mar 24, 2024 am 10:27 AM

Vivox100s parameter configuration revealed: How to optimize processor performance? In today's era of rapid technological development, smartphones have become an indispensable part of our daily lives. As an important part of a smartphone, the performance optimization of the processor is directly related to the user experience of the mobile phone. As a high-profile smartphone, Vivox100s's parameter configuration has attracted much attention, especially the optimization of processor performance has attracted much attention from users. As the &quot;brain&quot; of the mobile phone, the processor directly affects the running speed of the mobile phone.

How to use PHP functions to process JSON data? How to use PHP functions to process JSON data? May 04, 2024 pm 03:21 PM

PHP provides the following functions to process JSON data: Parse JSON data: Use json_decode() to convert a JSON string into a PHP array. Create JSON data: Use json_encode() to convert a PHP array or object into a JSON string. Get specific values ​​of JSON data: Use PHP array functions to access specific values, such as key-value pairs or array elements.

What are some ways to resolve inefficiencies in PHP functions? What are some ways to resolve inefficiencies in PHP functions? May 02, 2024 pm 01:48 PM

Five ways to optimize PHP function efficiency: avoid unnecessary copying of variables. Use references to avoid variable copying. Avoid repeated function calls. Inline simple functions. Optimizing loops using arrays.

See all articles