javascript - 如何根据 csv 中的值将这个 csv 字符串(也是 csvs)减少为一个对象嵌套 4 层深的数组?
问题描述
下面是包含我尝试做的事情的代码,以及嵌套结构应该导致的底部的一些有用的评论和示例。我相当有信心这可以用 .reduce 完成()但如果有人可以分享如何,或者如果我完全以错误的方式接近这个,请帮助指导我!
注意:我知道我的代码有很多问题,也可能是伪代码!基本上我遇到的主要问题是我不知道如何避免重写重复的键以及迭代当前的子项以将它们作为对象累积到各自的数组中。
const util = require("util");
const bootcampInfoString = require("../data(json)/scrapedBootcamps");
console.log(
util.inspect(
Object.values(bootcampInfoString) //
.join(",") // returns a template literal that basically mirrors the source file
.split("\n") // returns an array of comma-separated-values with the shape 'School,State,Grads,Company' e.g. 'Dev Bootcamp,CA,14,Amazon',
.reduce((arr, cv, idx) => {
const currentValueArray = cv.split(","); // splits those values into a more specific sub-array on each iteration
const schoolName = currentValueArray[0]; // represents the "school name" value
const company = currentValueArray[3];
const grads = parseInt(currentValueArray[2]);
const state = currentValueArray[1];
// return (
// arr[state]
// ? arr[state].push({
// name: "schools",
// children: [
// arr[state][schoolName]
// ? arr[state][schoolName].push({
// name: "companies",
// children: [
// arr[state][schoolName][company]
// ? arr[state][schoolName][company].push({
// name: company,
// value: grads,
// })
// : (arr[state][schoolName][company] = []),
// ],
// })
// : (arr[state][schoolName] = []),
// ],
// })
// : (arr[state] = []),
// arr
// );
return (
arr.push({
[!name && name]: state,
children: [
...this.children,
{
[!name && name]: schoolName,
children: [
...this.children,
{
[!name && name]: company,
value: grads,
},
],
},
],
}),
arr
);
}, []),
{ maxArrayLength: null, depth: null }
)
);
// let final = {
// name: 'states',
// children: [
// {
// name: 'WA',
// children: [
// {
// name: 'Nucamp Coding Bootcamp',
// children: [
// {
// name: 'Walgreens',
// value: 3
// }
// ]
// }
// ]
// }
// ]
// }
解决方案
推荐阅读
- django - 大行数据集上的 Django 过滤查询慢
- reactjs - React/Redux 不能正确更新状态,不能在组件中使用
- angular - 无法解析 Lightbox 的所有参数:([object Object]、[object Object]、[object Object]、[object Object]、[object Object]、?)
- go - 如何使用 Golang 解析 ndjson 文件?
- botframework - 增加 MS Teams 频道的自适应卡片宽度
- php - 如何获取此特定请求的实例?
- postgresql - 表“token”缺少 FROM 子句条目
- python - Python如何乘以非方阵?
- javascript - Paper js限制总路径长度
- winforms - Janu Gridex EndCustomEdit 事件