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

How to optimize JSON data grouping in JS

php中世界最好的语言
php中世界最好的语言Original
2018-04-14 10:14:351909browse

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"}
]

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'
  }
 ]
 }
]

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

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 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 ++
  }
 }
 })

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"};

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 above str1, you must use the following to convert it into a JSON object first:

  //由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 it like this:

  Alert(obj.name);
  Alert(obj.sex);

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字符

Or

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

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