简体   繁体   English

JS reduce:对象累加器标题

[英]JS reduce: object accumulator titles

I am experimenting with the reduce function at the moment and wondering if I can tailor the accumulator's keys' name to be a specific value?我目前正在试验 reduce 函数,想知道是否可以将累加器的键名定制为特定值?

For example, the below code returns {16 years of experience: ... } but I would like the return results to be categorized like the below:例如,下面的代码返回 {16 years of experience: ... } 但我希望返回结果分类如下:

Results wanted in this format:

{ Over 10 years:
  16: {
    {name: "Company One", category: "Finance", start: 1981, end: 2003},
    {name: "Company Two", category: "Retail", start: 1992, end: 2008}

  },


  20: { 
  {name: "Company One", category: "Finance", start: 1981, end: 2003},
  {name: "Company Two", category: "Retail", start: 1992, end: 2008}
  }

  ...
} etc...


const companies = [
    {name: "Company One", category: "Finance", start: 1981, end: 2003},
    {name: "Company Two", category: "Retail", start: 1992, end: 2008},
    {name: "Company Three", category: "Auto", start: 1999, end: 2007},
    {name: "Company Four", category: "Retail", start: 1989, end: 2010},
    {name: "Company Five", category: "Technology", start: 2009, end: 2014},
    {name: "Company Six", category: "Finance", start: 1987, end: 2010},
    {name: "Company Seven", category: "Auto", start: 1986, end: 1996},
    {name: "Company Eight", category: "Technology", start: 2011, end: 2016},
    {name: "Company Nine", category: "Retail", start: 1981, end: 1989}
  ];
  

const industryExeperience = (obj, keyStart, keyEnd)=>{
  return obj.reduce((exp, curObj)=>{
    let differences = curObj[keyEnd] - curObj[keyStart];
    console.log(differences)
    if(differences > 10){
      exp[differences + ' years of experience'] = curObj

    }
    return exp
  },{})
}

console.log(industryExeperience(companies, 'start', 'end'))



To group by years use the difference as keys and an array as values.要按年份分组,使用差异作为键,使用数组作为值。 Push or concat each item into existing array or add new one as needed将每一项推送或连接到现有数组中或根据需要添加新的

 const companies = [ {name: "Company One", category: "Finance", start: 1981, end: 2003}, {name: "Company Two", category: "Retail", start: 1992, end: 2008}, {name: "Company Three", category: "Auto", start: 1999, end: 2007}, {name: "Company Four", category: "Retail", start: 1989, end: 2010}, {name: "Company Five", category: "Technology", start: 2009, end: 2014}, {name: "Company Six", category: "Finance", start: 1987, end: 2010}, {name: "Company Seven", category: "Auto", start: 1986, end: 1996}, {name: "Company Eight", category: "Technology", start: 2011, end: 2016}, {name: "Company Nine", category: "Retail", start: 1981, end: 1989} ]; const grouped = companies.reduce((a,c)=>{ const diff = c.end - c.start; a[diff] = (a[diff] || []).concat(c) return a; },{}) console.log(grouped)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM