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

How to implement JSON data grouping optimization in Javascript

亚连
Release: 2018-06-19 11:45:42
Original
1927 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template