Home Web Front-end JS Tutorial How to implement JSON data grouping optimization in Javascript

How to implement JSON data grouping optimization in Javascript

Jun 19, 2018 am 11:45 AM
js json

This article mainly introduces the practice of JSON data grouping optimization in Javascript. The article also summarizes the essentials of JS operating JSON. Friends who need it can refer to it.

There is a bunch of data now. I need to sort it by time. Grouping for front-end view presentation

[
 {"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

needs to be transformed 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 network

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 optimization is 50%, about 1.5 ms!

3. Performance optimization practice

Because the dates in my array are arranged in order and there are no duplicates, you can consider removing the first The efficiency of 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][&#39;data&#39;].push(item)
  } else {
  nList.push({
   date: item.date,
   data: [item]
  })
  _nkey ++
  }
 }
 })
Copy after login

is optimized again by 50%, about 1ms!

PS: JS operation JSON summary

JSON (JavaScript Object Notation) is a lightweight data exchange format that uses completely independent Language-specific text format, ideal for data exchange. At the same time, JSON is a JavaScript native format, which means that 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: objects and arrays.

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 quotes; the value must be enclosed in parentheses if it is a string, but not if it is a numeric value. 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 = &#39;{ "name": "cxh", "sex": "man" }&#39;;
Copy after login

JSON object:

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

1. Convert JSON string to JSON object

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

  //由JSON字符串转换为JSON对象
var obj = eval(&#39;(&#39; + str + &#39;)&#39;);
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 like this:

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

Special attention: If obj is originally a JSON object, then after using the eval() function to convert it (even if it is converted multiple times) it will still be a JSON object, but after using the parseJSON() function to process it, it will In doubt (throws 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

Note:

Above Among the many methods, except that the eval() function comes with js, many other methods come from the json.js package. The new version of JSON has modified the API, injecting both JSON.stringify() and JSON.parse() methods into the built-in objects of Javascript. The former becomes Object.toJSONString(), and the latter 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.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

About using bootstrap-table.js to implement extended paging toolbar function

About substring() and substr( ) (detailed tutorial)

How to determine whether a variable name exists in an array in JavaScript

The above is the detailed content of How to implement JSON data grouping optimization in Javascript. 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)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

What is the difference between MySQL5.7 and MySQL8.0? What is the difference between MySQL5.7 and MySQL8.0? Feb 19, 2024 am 11:21 AM

MySQL5.7 and MySQL8.0 are two different MySQL database versions. There are some main differences between them: Performance improvements: MySQL8.0 has some performance improvements compared to MySQL5.7. These include better query optimizers, more efficient query execution plan generation, better indexing algorithms and parallel queries, etc. These improvements can improve query performance and overall system performance. JSON support: MySQL 8.0 introduces native support for JSON data type, including storage, query and indexing of JSON data. This makes processing and manipulating JSON data in MySQL more convenient and efficient. Transaction features: MySQL8.0 introduces some new transaction features, such as atomic

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.

Pandas usage tutorial: Quick start for reading JSON files Pandas usage tutorial: Quick start for reading JSON files Jan 13, 2024 am 10:15 AM

Quick Start: Pandas method of reading JSON files, specific code examples are required Introduction: In the field of data analysis and data science, Pandas is one of the important Python libraries. It provides rich functions and flexible data structures, and can easily process and analyze various data. In practical applications, we often encounter situations where we need to read JSON files. This article will introduce how to use Pandas to read JSON files, and attach specific code examples. 1. Installation of Pandas

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

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

In-depth understanding of PHP: Implementation method of converting JSON Unicode to Chinese In-depth understanding of PHP: Implementation method of converting JSON Unicode to Chinese Mar 05, 2024 pm 02:48 PM

In-depth understanding of PHP: Implementation method of converting JSONUnicode to Chinese During development, we often encounter situations where we need to process JSON data, and Unicode encoding in JSON will cause us some problems in some scenarios, especially when Unicode needs to be converted When encoding is converted to Chinese characters. In PHP, there are some methods that can help us achieve this conversion process. A common method will be introduced below and specific code examples will be provided. First, let us first understand the Un in JSON

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles