English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
There is a pile of data, I need to group it by time to present it in the front-end view
[ {"date":"2017-12-22"","start_time":"10:00:00","end_time":"10:00:00","status":"Performance Time"}, {"date":"2017-12-22"","start_time":"10:4"0: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:4"0:00","end_time":"10:40:00,"status":"Performance Time"} ]
Need 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' } ] } ]
1.Original method, a lot of networks
var map = { nList = [] //Traverse the original array for (var i = 0; i < arr.length; i++) { var item = arr[i] //If map does not exist, add it to the new nList if (!map[item.date]) { nList.push({}) date: item.date, data: [item] ) map[item.date] = item else { //Traverse nList for (var j = 0; j < nList.length; j++) { var nItem = nList[j], //If a date that matches is found, add it if (nItem.date == item.date) { nItem.data.push(item) //Exit the loop break } } } }
Running Efficiency: Traversal1000 appointments3ms, always felt not elegant, and didn't use ES5.features, so I decided to optimize it myself!
2.Using ES5Feature
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 { //Because forEach does not support break, so we use every to implement nList.every((nItem) => { if (nItem.date === item.date) { nItem.data.push(item) return false } return true ) } )
Performance Optimization50%, about1.5ms!
3.Performance Optimization Practice
Because the dates in my array are arranged in order and there are no duplicates, we can consider removing the second loop
let map = { nList = [] //Set the initial key to 0 let _nkey = 0 arr.forEach((item, index) => { if (index === 0) { nList.push({}) date: item.date, data: [item] ) else { let oItem = arr[index - 1] //and the previous date is consistent, then add it to the current one, otherwise add it to nList if (item.date === oItem.date) { nList[_nkey]['data'].push(item) else { nList.push({}) date: item.date, data: [item] ) _nkey ++ } } )
Efficiency optimization again50%, about1ms!
PS: Summary of JS operating on JSON
JSON (JavaScript Object Notation) is a lightweight data interchange format that uses a completely language-independent text format and is an ideal data interchange format. At the same time, JSON is a native format of JavaScript, which means that there is no need for any special API or toolkit to process JSON data in JavaScript.
This article mainly summarizes the key points of JavaScript operating on JSON.
There are two structures in JSON: objects and arrays.
1. An object starts with "{" (left parenthesis) and ends with "}" (right parenthesis). Each 'name' is followed by a ":" (colon);/. Values are separated by "," (comma) between 'key' and 'value'. Names are enclosed in quotes; if the value is a string, it must be enclosed in parentheses, while numeric values do not require them. 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 square bracket) and ends with "]" (right square bracket). Values are separated by "," (comma).
For example:
var jsonranklist=[{"xlid":"cxh","xldigitid":123456,"topscore":2000,"topplaytime":"2009-08-20"},{"xlid":"zd","xldigitid":123456,"topscore":1500,"topplaytime":"2009-11-20"}];
To facilitate the processing of JSON data, 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, i.e., a string, while JavaScript operates on JSON objects. Therefore, the conversion between JSON objects and JSON strings is crucial. 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 above str1It is necessary to convert it into a JSON object first using the following method:
//Convert JSON string to JSON object var obj = eval('(' + str + ');
Or
var obj = str.parseJSON(); //Convert JSON string to JSON object
Or
var obj = JSON.parse(str); //Convert JSON string to JSON object
Then, you can read it like this:
Alert(obj.name); Alert(obj.sex);
Special attention: If obj is already a JSON object, then after conversion using the eval() function (even after multiple conversions), it is still a JSON object, but after processing with the parseJSON() function, there may be questions (throw syntax errors).
Secondly, you can use toJSONString() or the global principle JSON.stringify() to convert a JSON object to a JSON string.
For example:
var last=obj.toJSONString(); //Convert JSON object to JSON character
Or
var last=JSON.stringify(obj); //Convert JSON object to JSON character alert(last);
Attention:
Among the many principles, except for the eval() function, which is built into JS, the other principles come from the json.js package. The new version of JSON has modified the API, injecting both JSON.stringify() and JSON.parse() principles into the built-in object of Javascript, the former becoming Object.toJSONString(), and the latter becoming String.parseJSON(). If the prompt indicates that the toJSONString() and parseJSON() principles cannot be found, it means that your json package version is too low.
Statement: The content of this article is from the network, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report violations, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)