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

获取数组长度并推入每个对象

  •  0
  • Matt  · 技术社区  · 2 年前

    我有一个功能

    const output = {}
    sites.forEach(obj=>{
        const ids = obj.ids
        if(ids && ids.length>0){
            ids.forEach(id=>{
                if(!output[id]){
                    output[id] = []
                }
                output[id].push(obj.url);
            });
        }
    });
    
    fs.writeFileSync('cleanedData.json', JSON.stringify(output));
    

    获取以下数据:

    { 
         url: "www.site.com", 
         ids: ["F20", "C10", "C05"] 
    }, 
    { 
        url: "www.site.com/something", 
        ids: ["F20", "C05", "C10"] 
    }, 
    { 
        url: "www.site.com/somethingelse", 
        ids: ["F20", "C12", "C05"] 
    }
    

    并对其进行转换,以便我有一个包含所有id和具有该id的所有URL的列表:

    {
      "F20": [
        "www.site.com",
        "www.site.com/something",
        "www.site.com/somethingelse"
      ]
    }, {
      "C10": [
        "www.site.com",
        "www.site.com/something"
      ]
    }, {
      "C12": [
        "www.site.com/somethingelse"
      ]
    }, {
      "C05": [
        "www.site.com",
        "www.site.com/something",
        "www.site.com/somethingelse"
      ]
    }
    

    我可以使用

    console.log(Object.values(output).map(id => id.length))
    

    但我不知道如何将其作为forEach的一部分,所以我在每个对象中都有一个键/值来显示数组的长度。

    1 回复  |  直到 2 年前
        1
  •  1
  •   Barmar Eduardo López    2 年前

    在输出中使用嵌套对象,并为其指定 length 属性,该属性在推送到数组上时递增。

    const sites = [{
        url: "www.site.com",
        ids: ["F20", "C10", "C05"]
      },
      {
        url: "www.site.com/something",
        ids: ["F20", "C05", "C10"]
      },
      {
        url: "www.site.com/somethingelse",
        ids: ["F20", "C12", "C05"]
      }
    ];
    
    const output = {};
    sites.forEach(obj => {
      const ids = obj.ids
      if (ids && ids.length > 0) {
        ids.forEach(id => {
          if (!output[id]) {
            output[id] = {length: 0, urls: []}
          }
          output[id].urls.push(obj.url);
          output[id].length++;
        });
      }
    });
    
    console.log(output);
        2
  •  0
  •   Yosvel Quintero    2 年前

    您可以使用 Array.prototype.reduce() 与…结合 Array.prototype.forEach() :

    const sites = [{url: "www.site.com",ids: ["F20", "C10", "C05"]},{url: "www.site.com/something",ids: ["F20", "C05", "C10"]},{url: "www.site.com/somethingelse",ids: ["F20", "C12", "C05"]}]
    
    const output = sites.reduce((a, { url, ids }) => {
      ids.forEach(id => {
        a[id] = a[id] || { length: 0, urls: [] }
        a[id].length += 1
        a[id].urls.push(url)
      })
      return a
    }, {})
    
    console.log(output)