如何使用groupby从JSON获取数据以及如何使用lodash进行过滤

时间:2018-07-10 08:44:30

标签: javascript json

我只需要从json文件中获取单个数据,我正在使用lodash .groupBy和.filter,但只会抛出错误的结果

let insightAverageThroughput = [{
    "insight": "wahahahah",
    "reportMonth": "June 2018",
    "project": "Cambridge Core Dashboard"
  },
  {
    "insight": "aaaaaaa",
    "reportMonth": "February 2018",
    "project": "coreadmin"
  }
];

function filterInsights(data, month, project) {
  let grouped = _.groupBy(data, z => z.project == project)
  console.log(month)
  console.log(project)
  console.log(grouped)
  let filtered = _.filter(grouped[project], x => x.reportMonth == month)
  console.log(filter)
  return filtered.length > 0 && filtered[0].insight;
}

2 个答案:

答案 0 :(得分:2)

您应该groupBy仅按项目而不按谓词:

  let grouped = _.groupBy(data, z => z.project)

答案 1 :(得分:0)

使用groupBy,所有数据将按一个项目进行分组,并使用filter返回满足条件reportMonth === month的所有项目。

还请注意我如何使用groupBy。您应该传递一个值,而不是条件:

_.groupBy(data, 'project')

这是代码

let insightAverageThroughput = [{
    "insight": "wahahahah",
    "reportMonth": "June 2018",
    "project": "Cambridge Core Dashboard"
  },
  {
    "insight": "aaaaaaa",
    "reportMonth": "February 2018",
    "project": "coreadmin"
  }
];

function filterInsights(data, month, project) {
  const grouped = _.groupBy(data, 'project')
  const filteredItems = grouped[project].filter(({ reportMonth }) => reportMonth === month)
  
  return { [project]: filteredItems }
}

console.log(filterInsights(insightAverageThroughput, 'February 2018', 'coreadmin'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.2.1/lodash.min.js"></script>


可以在ES6中实现相同的逻辑(无需外部库)。仅使用reduce的方式如下:

let insightAverageThroughput = [{
    "insight": "wahahahah",
    "reportMonth": "June 2018",
    "project": "Cambridge Core Dashboard"
  },
  {
    "insight": "aaaaaaa",
    "reportMonth": "February 2018",
    "project": "coreadmin"
  }
];

function filterInsights(data, month, project) {
  return data.reduce((accumulator, item) => { 

    if (item.project === project && month === item.reportMonth) {
      accumulator[project].push(item)
    }
    
    return accumulator
  } , { [project]: [] })
}

console.log(filterInsights(insightAverageThroughput, 'February 2018', 'coreadmin' ))