代码之家  ›  专栏  ›  技术社区  ›  jmarc

使用Javascript计算JSON嵌套数组中值的重复次数

  •  0
  • jmarc  · 技术社区  · 7 年前

    我被一些我认为很简单的事情困住了。假设我有一个这样的物体。我试图在div中插入被标记的动物的每个名称,以及该标记在类型中的次数(例如,cat=3等)

    var animals = '';
    animals = {
      "types": [
        {
          "id": "1",
          "tags": ["cat"]
        },
        {
          "id": "2",
          "tags": ["dog"]
        },
        {
          "id": "3",
          "tags": ["cat", "bird", "dog"]
        },
        {
          "id": "4",
          "tags": []
        },
        {
          "id": "5",
          "tags": ["cat", "bird"]
        }
      ]
    }
    
    for (var i = 0; i < animals.length; i++) {
      var tags = animals[i].tags;
    }
    <div class="types">Number of animals:</div>

    我是一个使用复杂JSON对象的初学者,如果有任何帮助,我将不胜感激。它可以是vanilla JS或Jquery。

    谢谢!

    7 回复  |  直到 7 年前
        1
  •  1
  •   cdoshi    7 年前

    查看下面的代码片段,第一个循环迭代并计算每个动物的数量。

    第二个填充你的div

    var animals = '';
    animals = {
      "types": [{
          "id": "1",
          "tags": ["cat"]
        },
        {
          "id": "2",
          "tags": ["dog"]
        },
        {
          "id": "3",
          "tags": ["cat", "bird", "dog"]
        },
        {
          "id": "4",
          "tags": []
        },
        {
          "id": "5",
          "tags": ["cat", "bird"]
        }
      ]
    }
    var tags = {};
    
    // Iterate over all your items
    animals.types.forEach(function(type) {
      // Iterate over all the animals in the array
      type.tags.forEach(function(tag) {
        if (tag in tags) {
          // If animal is present, increment the count
          tags[tag] = tags[tag] + 1;
        } else {
          // If animal is not present, add the entry
          tags[tag] = 1;
        }
      })
    })
    
    // Iterate over all the animals and add it to the div
    for (var animal in tags) {
      if (tags.hasOwnProperty(animal)) {
        document.getElementsByClassName('types')[0].innerHTML += ' ' + animal + ' ' + tags[animal];
      }
    }
    <div class="types">Number of animals:</div>
        2
  •  1
  •   Jagjeet Singh    7 年前

    你可以这样用 map()

    var animals = {
      "types": [{
        "id": "1",
        "tags": ["cat"]
       },
       {
        "id": "2",
        "tags": ["dog"]
       },
       {
        "id": "3",
        "tags": ["cat", "bird", "dog"]
       },
       {
        "id": "4",
        "tags": []
       },
       {
        "id": "5",
        "tags": ["cat", "bird"]
       }
      ]
     };
    
     var count = {};
     animals.types.map(function (arr, i) {
      arr.tags.map(function (tag, k) {
       count[tag] = (count[tag] || 0) + 1;
      });
     });
     console.log(count);
        3
  •  1
  •   Akrion    7 年前

    如果你使用 reduce &安培; destrucuring 变成一行:

    var animals = {
      "types": [{
          "id": "1",
          "tags": ["cat"]
        },
        {
          "id": "2",
          "tags": ["dog"]
        },
        {
          "id": "3",
          "tags": ["cat", "bird", "dog"]
        },
        {
          "id": "4",
          "tags": []
        },
        {
          "id": "5",
          "tags": ["cat", "bird"]
        }
      ]
    }
    
    console.log(
       animals.types.reduce((r,{tags}) => tags.map(tag => r[tag] = (r[tag] || 0) + 1) && r, {})
    )
        4
  •  0
  •   Hassan Sadeghi    7 年前

    试试这个简单的方法:

    var animals = { "types": [ { "id": "1", "tags": ["cat"] }, { "id": "2", "tags": ["dog"] }, { "id": "3", "tags": ["cat", "bird", "dog"] }, { "id": "4", "tags": [] }, { "id": "5", "tags": ["cat", "bird"] } ] }
    var finalRes={};
    animals.types.map(function(o, i){
    o.tags.map(function(p, j){
        finalRes[p]=(finalRes[p]||0)+1;
    });
    });
    console.log(finalRes);
    

    { cat: 3, dog: 2, bird: 2 }
    

    对不起,我用手机打字,速度慢但正确!

        5
  •  0
  •   skylerfenn    7 年前
    1. 将所有标记展平为单个数组
    2. 根据需要处理标记计数

    const animals = {
      "types": [
        {
          "id": "1",
          "tags": ["cat"]
        },
        {
          "id": "2",
          "tags": ["dog"]
        },
        {
          "id": "3",
          "tags": ["cat", "bird", "dog"]
        },
        {
          "id": "4",
          "tags": []
        },
        {
          "id": "5",
          "tags": ["cat", "bird"]
        },
      ],
    };
    
    // Flatten all tags into single array
    
    var allTags = [].concat(
      ...animals.types.map(
        (type) => type.tags
      )
    );
    
    // Count each tag
    
    const tagsCount = {};
    
    allTags.forEach(
      (tag) => tagsCount[tag] = tagsCount[tag] ? tagsCount[tag] + 1 : 1 
    )
      
    // Handle tag count as you need
    
    const app = document.querySelector('#app');
    
    app.innerHTML = Object.keys(tagsCount).map((key) => {
      return `<p>${key}: ${tagsCount[key]}</p>`
    }).join('');
    <h1>Number of Animal Types</h1>
    
    <div id="app"></div>
        6
  •  0
  •   Priya Sajeetharan    7 年前

    基本的javascript用法。

    // var animals = ''; // not needed
    var animals = {
      "types": [{
          "id": "1",
          "tags": ["cat"]
        },
        {
          "id": "2",
          "tags": ["dog"]
        },
        {
          "id": "3",
          "tags": ["cat", "bird", "dog"]
        },
        {
          "id": "4",
          "tags": []
        },
        {
          "id": "5",
          "tags": ["cat", "bird"]
        }
      ]
    };
    
    var counts = {};
    for (var i = 0; i < animals.types.length; i++) { // types is a key in animals object, animals is not an array
      var tags = animals.types[i].tags;
      if (tags.length > 0) {
        for (var j = 0; j < tags.length; j++) {
          var tag = tags[j];
          if (typeof counts[tag] === 'undefined') {
            counts[tag] = 0;
          }
          counts[tag]++;
        }
      }
    }
    
    
    console.log(counts);
        7
  •  0
  •   Hiteshdua1    7 年前

    你可以创建一个 hash map types.tags 阵列

    var animals = '';
    animals = {
      "types": [
        {
          "id": "1",
          "tags": ["cat"]
        },
        {
          "id": "2",
          "tags": ["dog"]
        },
        {
          "id": "3",
          "tags": ["cat", "bird", "dog"]
        },
        {
          "id": "4",
          "tags": []
        },
        {
          "id": "5",
          "tags": ["cat", "bird"]
        }
      ]
    }
    let types = animals.types;
    var counts = {};
    
    for (var i = 0; i < types.length; i++) {
      types[i].tags.forEach((x) => { 
          counts[x] = (counts[x] || 0)+1; 
         });
    }
    console.log(counts);
    <div class="types">Number of animals:</div>