How to implement JSON data grouping optimization in Javascript
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"} ]
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' } ] } ]
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 } } } }
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 }) } })
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]['data'].push(item) } else { nList.push({ date: item.date, data: [item] }) _nkey ++ } } })
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"};
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"}];
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" }';
JSON object:
var str2 = { "name": "cxh", "sex": "man" };
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('(' + str + ')');
or
var obj = str.parseJSON(); //由JSON字符串转换为JSON对象
or
var obj = JSON.parse(str); //由JSON字符串转换为JSON对象
Then, you can Read like this:
Alert(obj.name); Alert(obj.sex);
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字符
Or
var last=JSON.stringify(obj); //将JSON对象转化为JSON字符 alert(last);
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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 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.

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

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

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 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: 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.
