Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
如果您愿意使用 lodash 或 下划线,这是一个解决方案:
const response = [{ area: "Z", val: "work", count: 12, data: "2022-03-01T00:00:00" }, { area: "Z", val: "not work", count: 41, data: "2022-04-01T00:00:00" }, { area: "R", val: "work", count: 55, data: "2022-03-01T00:00:00" }, { area: "R", val: "not work", count: 62, data: "2022-04-01T00:00:00" } ]; const group = _.groupBy(response, 'area'); const result = _.map(_.keys(group), i => { return { area: i, count: _.map(group[i], j => { return { [j.data.substring(0, 7)]: { [j.val]: j.count } } }) } }) console.log('result', result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
这是一个简单的 JS 解决方案。
const response = [{ area: "Z", val: "work", count: 12, data: "2022-03-01T00:00:00" }, { area: "Z", val: "not work", count: 41, data: "2022-04-01T00:00:00" }, { area: "R", val: "work", count: 55, data: "2022-03-01T00:00:00" }, { area: "R", val: "not work", count: 62, data: "2022-04-01T00:00:00" } ]; const groupBy = (arr, key) => { const initialValue = {}; return arr.reduce((acc, cval) => { const myAttribute = cval[key]; acc[myAttribute] = [...(acc[myAttribute] || []), cval] return acc; }, initialValue); }; const group = groupBy(response, 'area'); const result = Object.keys(group).map(i => { return { area: i, count: group[i].map(j => { return { [j.data.substring(0, 7)]: { [j.val]: j.count } } }) } }) console.log(result)
If you are open to use lodash or underscore, here is a solution:
This is a plain JS solution.
因为您的 count 语法无效。我假设它是一个对象数组。使用reduce可以轻松解决这些分组问题
count
reduce
const response = [{ area: "Z", val: "work", count: 12, data: "2022-03-01T00:00:00" },{ area: "Z", val: "not work", count: 41, data: "2022-04-01T00:00:00" },{ area: "R", val: "work", count: 55, data: "2022-03-01T00:00:00" },{ area: "R", val: "not work", count: 62, data: "2022-04-01T00:00:00" }]; const res = Object.values(response.reduce((acc,{area,val,count,data}) => { if(!acc[area])acc[area]={area: area, count:[]} acc[area]['count'].push({[data.substring(0,7)] : {[val]:count}}) return acc },{})) console.log(res)
since your count is not valid syntax. i assumed it is an array of objects.These grouping problems are easily solvable using reduce
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
暂无简介
文章 0 评论 0
接受
发布评论
评论(2)
如果您愿意使用 lodash 或 下划线,这是一个解决方案:
这是一个简单的 JS 解决方案。
If you are open to use lodash or underscore, here is a solution:
This is a plain JS solution.
因为您的
count
语法无效。我假设它是一个对象数组。使用
reduce
可以轻松解决这些分组问题since your
count
is not valid syntax. i assumed it is an array of objects.These grouping problems are easily solvable using
reduce