【问题标题】:JSON object return of an array of objects which contains the keys and its valuesJSON 对象返回包含键及其值的对象数组
【发布时间】:2022-02-06 17:09:44
【问题描述】:

Boris 列出了他的酒吧里所有可用的啤酒,但那是一团糟。他希望看到按品牌分组的啤酒。 Boris 还告诉您,该函数应该返回一个对象数组,其中包含品牌名称和该品牌的啤酒 ID 数组。

带有数据的 JSON 文件: https://challenge.codingsans.com/beers.json

输出示例:

[
  {
    "brand": "brandName2",
    "beers": [
      "beerID3",
      "beerID4"
    ]
  },
  {
    "brand": "brandName1",
    "beers": [
      "beerID2",
      "beerID1"
    ]
  }
]

//

我已经这样做了: (所以基本上什么都没有。我只是想知道如何解决它。)

request = new XMLHttpRequest;
request.open('GET', 'https://challenge.codingsans.com/beers.json', true);
var data = [];
request.onload = function() {
    if (request.status >= 200 && request.status < 400) {
        // Date Parse
        data = JSON.parse(request.responseText);
        // Success!

        // Arrays 
        var beerIDs = [];
        var beerBrand = [];
        // Iteration

        for (var key in data) {
            beerIDs.push(data[key].id);
            beerBrand.push(data[key].brand);
            // console.log(beerIDs);
            // console.log(beerBrand);
        }
        console.log(beerIDs);
        console.log(beerBrand);


        //final list

        var finalList = [];


    } else {
        // We reached our target server, but it returned an error
    }
};

request.onerror = function() {
    // There was a connection error of some sort
};

request.send();

【问题讨论】:

    标签: javascript arrays object filter nested


    【解决方案1】:

    试试这个:

    request = new XMLHttpRequest;
    request.open('GET', 'https://challenge.codingsans.com/beers.json', true);
    var data = [];
    request.onload = function() {
      if (request.status >= 200 && request.status < 400) {
        // Date Parse
        data = JSON.parse(request.responseText);
        // Success!
            
            
        const organizedBeers = data.reduce((acc, beers) => {
          
          const findIndex = acc.findIndex(beer => beer.brand === beers.brand)
    
          if(findIndex > -1) {
    
            acc[findIndex].beersId.push(beers.id)
    
          } else {
    
            acc.push({
              brand: beers.brand,
              beersId: [beers.id],
            })
    
          }
              
          return acc;
        }, [])
    
       console.log(organizedBeers)
            
            
      } else  {
        // We reached our target server, but it returned an error
      }
    };
    
    request.onerror = function() {
        // There was a connection error of some sort
    };
    
    request.send();
    

    【讨论】:

      【解决方案2】:

      因此,基本上,您可以创建一个新数组作为最终输出(在我们的例子中,假设为“aBeerNBrands”)。您可以在那里推送具有所需属性的新对象(如“品牌”:字符串、ID:数组)。 然后您可以遍历主数组(在您的情况下为:'data')元素并在嵌套循环中检查该品牌对象是否存在于新数组('aBeerNBrands')中,如果存在则推送 id到 aBeerNBrands 对象中存在的 ids 数组;否则在“aBeerNBrands”内创建具有所需属性的新对象。下面的代码可以满足您的要求。

      request = new XMLHttpRequest;
      request.open('GET', 'https://challenge.codingsans.com/beers.json', true);
      var data = [];
      request.onload = function() {
      debugger;
          if (request.status >= 200 && request.status < 400) {
              // Date Parse
              data = JSON.parse(request.responseText);
              // Success!
      
              // Arrays 
              var aBeerNBrands = [];
              
              // Iteration
      
              for (var key in data) {
                  if(aBeerNBrands.length > 0){
                    for(var key2 in aBeerNBrands){
                        if(aBeerNBrands[key2].brand === data[key].brand){
                                                  aBeerNBrands[key2].ids.push(data[key].id);
                            break;
                        } 
                        
                        if(key2 == aBeerNBrands.length - 1 && aBeerNBrands[key2].brand !== data[key].brand){
                          var oBrandObject = {
                           brand: data[key].brand,
                           ids: [data[key].id]
                          };
                          aBeerNBrands.push(oBrandObject);
                        }
                    }
                  } else{
                    var oBrandObject = {
                       brand: data[key].brand,
                       ids: [data[key].id]
                      };
                      aBeerNBrands.push(oBrandObject);
                    }
                  
                  // console.log(beerIDs);
                  // console.log(beerBrand);
              }
              
              console.log(aBeerNBrands);
      
      
      
          } else {
              // We reached our target server, but it returned an error
          }
      };
      
      request.onerror = function() {
          // There was a connection error of some sort
      };
      
      request.send();
      

      【讨论】:

        【解决方案3】:

        按照以下步骤:

        • 按品牌对对象的输入数组进行分组,并使用 Array.reduce() 方法生成一个对象。
        • 根据我们拥有的缩减品牌对象构建输出。

        工作演示:

        const data = [
          {
            "id": "ccw-1",
            "name": "Coding Challenge White",
            "brand": "Coding Challenge Brewery"
          }, {
            "id": "sw-1",
            "name": "Share White",
            "brand": "Share",
          }, {
            "id": "bspa-1",
            "name": "Beer Sans Pale Ale",
            "brand": "Beer Sans Brewery"
          }, {
            "id": "ccb-1",
            "name": "Coding Challenge Brown",
            "brand": "Coding Challenge Brewery"
          }, {
            "id": "ccw-2",
            "name": "Coding Challenge Wheat",
            "brand": "Coding Challenge Brewery"
          }];
          
        // result array
        const resultArr = [];
          
        // grouping by brand and resulting with an object using Array.reduce() method
        const groupByBrand = data.reduce((group, item) => {
          const { brand } = item;
          group[brand] = group[brand] ?? [];
          group[brand].push(item.id);
          return group;
        }, {});
        
        // Finally structuring the output based on the brand object we have.
        Object.keys(groupByBrand).forEach((item) => {
            resultArr.push({
              'brand': item,
              'beers': groupByBrand[item]
            })
        })
        
        // Result
        console.log(resultArr);

        【讨论】:

          猜你喜欢
          • 2021-05-04
          • 2017-07-15
          • 2021-10-08
          • 2015-07-02
          • 2019-10-21
          • 1970-01-01
          • 1970-01-01
          • 2013-10-02
          • 2021-11-17
          相关资源
          最近更新 更多