我想弄清楚如何将值分组。 例如,我想转换下面的数据
[
{"book": "Typescript 1", "year": "2015", "units": 1000},
{"book": "Javascript 1", "year": "2015", "units": 2000},
{"book": "Typescript1", "year": "2016", "units": 6000}
]
在
[
{
"book": "Typescript 1",
"series": [
{"year": "2015", "units": 1000},
{"year": "2016", "units": 6000}
]
},
{
"book": "Javascript 1",
"series": [
{"year": "2015", "units": 2000}
]
}
]
答案 0 :(得分:1)
请阅读"Why using _.chain
is a mistake."以及为何建议flow()
。
以下是从函数式编程角度解决问题的几个方法:
import tap from "lodash/fp/tap";
import flow from "lodash/fp/flow";
import groupBy from "lodash/fp/groupBy";
const map = require('lodash/fp/map').convert({ 'cap': false });
const result = flow(
groupBy('book'),
map((series, book) => ({book, series: series.map(({units, year}) =>
({year, units}) )})),
tap(console.log)
)(input)
其中input
是您要转换的数组。
答案 1 :(得分:0)
这是使用reduce()
和Object.values()
使用普通JavaScript的简洁方法:
NDict = lambda: None
NDict = lambda: defaultdict(NDict)
ouroboros = NDict()
ouroboros[1][2][3][4][5][6][7][8][9] = True
答案 2 :(得分:-1)
我将提供一种不使用打字稿的起点方法。如果您需要更多帮助,请告诉我们您的方法。
var original = [
{"book": "Typescript 1", "year": "2015", "units": 1000},
{"book": "Javascript 1", "year": "2015", "units": 2000},
{"book": "Typescript1", "year": "2016", "units": 6000}
];
const mapBook = new Map();
original.forEach((value) => {
const year = value['year'];
const book = value['book'];
const units = value['units'];
if(!mapBook.has(book)) {
const mapYear = new Map();
mapYear.set(year, units);
mapBook.set(book, mapYear);
} else {
const mapYear = mapBook.get(book);
if(mapYear.has(year)){
//Decide what to do if it is reapeted
} else {
mapYear.set(year, units);
mapBook.set(book, mapYear);
}
}
});
const mapBookIterator = mapBook.entries();
for(let [key, value] of mapBookIterator ){
//iterate your entries and build your object
console.log(key, value);
}