【问题标题】:Javascript condition in loop [duplicate]循环中的Javascript条件[重复]
【发布时间】:2019-03-22 21:52:45
【问题描述】:

这是我的输入:

    companyList: [
      {
        company_name: 'company1',
        item: 'item1'
      },
      {
        company_name: 'company1',
        item: 'item2'
      },
      {
        company_name: 'company1',
        item: 'item3'
      },
      {
        company_name: 'company2',
        item: 'item4'
      }
    ]

这就是我想要的输出:

    result: [
      {
        company_name: 'company1',
        product: [
          { item: 'item1'},
          { item: 'item2'},
          { item: 'item3'}
        ]
      },
      {
        company_name: 'company2',
        product: [
          { item: 'item4'}
        ]
      }
    ]

使用map,我怎样才能得到我的结果?

【问题讨论】:

标签: javascript arrays loops duplicates


【解决方案1】:

您可以遍历companyList 的数组并使用O(n) 复杂性获得所需的输出,如下所示:

var companyList = [{
  company_name: 'company1',
  item: 'item1'
}, {
  company_name: 'company1',
  item: 'item2'
}, {
  company_name: 'company1',
  item: 'item3'
}, {
  company_name: 'company2',
  item: 'item4'
}];

var tempObj = {};
companyList.forEach((companyObj) => {
  if(tempObj[companyObj.company_name]){
    tempObj[companyObj.company_name].product.push({item: companyObj.item});
  } else {
    tempObj[companyObj.company_name] = {
      company_name: companyObj.company_name,
      product: [{item: companyObj.item}]
    }
  }
});
var result = Object.values(tempObj);
console.log(result);

【讨论】:

    【解决方案2】:

    您可以使用reduce 创建新数组

    let companyList = [{
        company_name: 'company1',
        item: 'item1'
      },
      {
        company_name: 'company1',
        item: 'item2'
      },
      {
        company_name: 'company1',
        item: 'item3'
      },
      {
        company_name: 'company2',
        item: 'item4'
      }
    ]
    
    let result = companyList.reduce(function(acc, curr) {
      // use findIndex to get the index of the object where the comany_name matches
      let findIndex = acc.findIndex(function(item) {
        return item.company_name === curr.company_name;
      });
      // will get -1 is company_name does not exist
      if (findIndex === -1) {
        let obj = {};
        // then create new object and push the value to it
        obj.company_name = curr.company_name;
        obj.product = [{
          item: curr.item
        }];
        acc.push(obj)
      } else {
        // if company_name exist then update the product list
        acc[findIndex].product.push({
          item: curr.item
        })
      }
      return acc;
    }, []);
    console.log(result)

    【讨论】:

      猜你喜欢
      • 2018-10-02
      • 1970-01-01
      • 2016-01-19
      • 1970-01-01
      • 1970-01-01
      • 2014-11-08
      • 1970-01-01
      • 2022-07-06
      • 2017-06-04
      相关资源
      最近更新 更多