首页 > 解决方案 > 如何根据 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
//                         }
//                     ]
//                 }
//             ]
//         }
//     ]
// }

标签: javascriptcsvnestedreduce

解决方案


推荐阅读