Three methods of json format and deduplication

json format

   The json format is an array of objects and a complex data structure formed by nesting each other. The json itself can be an array or an object.

  Supplement: The quotation marks of the attribute name of the object can be added or not, but json data is often used for front-end and back-end interaction.

  If json data is used for front-end and back-end interaction, the attribute name of the object must be enclosed in double quotes.

    Example: var arr = [{

      'name': 'Komei'

      “age” : 17},

      {name: 'xiao',

      age :10}]

            var preson = {“name”: 'cxk'

      "Likes": ["sing", "jump", "rap"]}

Deduplication: Only one duplicate element is kept .

1. Double for loop, leaving only non-repetitive ones

  for(var i = 0; i < arr.length-1; i++){

    for(var j = i+1; j < arr.length; j++){

       if(arr[i] === arr[j]){

            arr.splice(j,1)  

            j--// After deletion, j-1 offsets j ++ in for to ensure that duplicate values ​​are not skipped

        }

      }

    }

2. Use object attribute names without conflict

  You can use numbers as attribute names of objects

   例 : var obj = {4 : lisi '}

  Traverse the array to determine whether the current array element can get the value as the object property name

  If it cannot be obtained, it means that this is the first time to traverse to the current value, and the current element is assigned as the object attribute name.

       If you get it, it means that the value has been assigned before, which means that the current value is not the first time it appears.

     Example: var arr = [4,2,4,5,6,6,74,1]

    var obj = {}

           var arr1 = []

          arr.forEach(function (item){

    // Use item as the property name to get the value in the object to see if it can be obtained

    if(obj[item]){

    // The value is obtained, indicating that the item is not the first time it appears, indicating that the item is an invalid value, so there is no need to push into arr1

    }else{

      // Can't get the value, indicating that the item appears for the first time, then give him a value and assign a meaningful value.

      // item is the first time it appears, he is the value we want to keep

      obj[item] = ‘a’

      arr.push(item)}

      }

3 , ES6 (Set is a new data type, an enhanced version of the array, the default is not allowed to repeat)

    Example: var arr = [5,6,7,3,25,6]

            var arr1 = Array.from(new Set(arr))

            console.log (arr1) // Complete deduplication

Guess you like

Origin www.cnblogs.com/52580587zl/p/12675662.html