当前位置: 首页 > 知识库问答 >
问题:

javascript - 怎么把数组arr转换成obj对象这种格式呢?

宇文嘉勋
2024-04-04

怎么把数组arr转换成obj对象这种格式呢

const arr = [    {root: '', dir: '', base: '11K', ext: '', name: '11K'},    {root: '', dir: '', base: '12K', ext: '', name: '12K'},    {        root: '',        dir: '11K',        base: 'KF32A158SQX',        ext: '',        name: 'KF32A158SQX'    },    {root: '', dir: '11K', base: 'tst', ext: '', name: 'tst'},    {        root: '',        dir: '11K\\KF32A158SQX',        base: 'KF32A158SQX-Port.xml',        ext: '.xml',        name: 'KF32A158SQX-Port'    },    {root: '', dir: '11K\\tst', base: 'djjd', ext: '', name: 'djjd'},    {        root: '',        dir: '11K\\tst\\djjd',        base: '1.txt',        ext: '.txt',        name: '1'    }]const obj = {    '11K':{        'KF32A158SQX':'KF32A158SQX-Port.xml',        'tst':{            'djjd':'1.txt'        }    },    '12K':{    }}const val = arr.reduce((acc, cur) => {    if (!cur.dir) {        acc[cur.base] = {}    } else {        if (Object.keys(acc).includes(cur.dir)) {            acc[cur.dir][cur.base] = {}        } else {            // let arr = cur.dir.split('\\')            // acc[arr[0]][[arr[1]]] = cur.base            if (cur.ext) {                // console.log('NO',cur)            } else {                console.log('YES',cur)                let arr = cur.dir.split('\\')            }        }    }    return acc}, {})console.log(val)

我这样处理只能获取第一层数据

共有4个答案

蓟辰沛
2024-04-04
interface FileTree {    [path: string]: FileTree | string}function createFile(tree: FileTree, info: (typeof arr)[0]): FileTree {    const [path, ...rest] = info.dir.split('\\'),        cf = () =>            createFile((tree[path] ??= {}) as FileTree, {                ...info,                dir: rest.join('\\')            })    if (info.ext.length === 0)        if (path.length === 0) tree[info.base] = {}        else cf()    else if (rest.length === 0) tree[path] = info.base    else cf()    return tree}console.log(arr.reduce(createFile, {}))
{  "11K": { KF32A158SQX: "KF32A158SQX-Port.xml", tst: { djjd: "1.txt" } },  "12K": {}}
杨凌
2024-04-04

在你原先的基础上修改一下就可以了

const cache = {};const val = arr.reduce((acc, cur) => {  if (!cur.dir) {    acc[cur.name] = {};    cache[cur.name] = acc[cur.name];  } else if (!cur.ext) {    cache[cur.dir][cur.name] = {};    cache[`${cur.dir}\\${cur.name}`] = cache[cur.dir][cur.name];  } else {    const dirs = cur.dir.split('\\');    const lastDir = dirs.pop();    const parentDir = dirs.join('\\');    cache[parentDir][lastDir] = cur.base;  }  return acc;}, {});console.log(val);
岳君之
2024-04-04

image.png

let isObject = obj => obj !== null && typeof obj === 'object'let dirToTree = (arr=[])=>{    return arr.reduce((acc,cur)=>{        let obj = acc;        cur.dir.split('\\').forEach((dirItem, dirIdx, dirArr)=>{            if(dirItem) {                 if((dirIdx+1)<dirArr.length) {                     // dir目录是否已创建                    obj[dirItem] = isObject(obj[dirItem]) ? obj[dirItem] : {}                    obj = obj[dirItem];                } else{                     // dir最后一个层级                   obj[dirItem] = cur.base                }            } else {                //  处理dir为空                obj[cur.base] = {}            }        });        return acc;     },{})}dirToTree(arr);

 注:有个BUG 对象只能是一个文件对应一个目录,一个目录对应不了多个文件。

芮安顺
2024-04-04

我看明白了name就是创建一个对象,dir就是挂载到哪里。

至于只有两层大概率是因为不是递归,或者没有排序。

所以可以考虑遍历两次,第一次构建,第二次完成数据结构。


image.png

const result = arr.reduce((s,n)=>{    if(n.dir){        const dir = n.dir.split('\\');        let current = s        // dir.forEach(v=>{        //     current = current[v]?current[v]:(current[v] = {})        // })        // current[dir.slice(-1)[0]] = n.name                dir.slice(0,-1).forEach(v=>{            // current = current[v]?current[v]:(current[v] = {})            if(_.isObject(current[v])){                current = current[v]            }else{                current[v] = {}                current = current[v]            }        })        current[dir.slice(-1)[0]] =n.name        //     Object.assign({},current[dir.slice(-1)[0]], {        //     // [dir.slice(-1)[0]]: n.name        // });    }else{        s[n.name] = s[n.name] || {};    }    return s;},{})console.log(JSON.stringify(result, null ,4))

重置了一次数据

 类似资料:
  • 想知道 js 字符串怎么转成数组对象,上面的转成下面的

  • 这是接口接受的类型: 这是我目前的: 因为接口接收一个JSON数组,类型1 的 value 需要变成 [''],其他类型就不用变。 这是我目前的写法

  • 问题内容: 我有一个WSDL文件,我需要将其转换为Java,为此,我使用下面链接中的分步过程 http://axis.apache.org/axis2/java/core/tools/eclipse/wsdl2java- plugin.html 就像将axis2 codegen jar文件添加到eclipse文件夹中的dropins文件夹中并重新启动eclipse一样,但是我在eclipse ID

  • 问题内容: 我正在开发一个Web应用程序,其中将在客户端和服务器端之间传输数据。 我已经知道JavaScript int!= Java int。因为,Java int不能为null,对。现在这是我面临的问题。 我将Java int变量更改为Integer。 我的问题在这里: 我不能在这里使用Integer变量。我尝试过, 但这会使事情变得更复杂。我们还有其他 转换方法或转换技术吗? 任何修复都会更

  • 问题内容: 如果我有: 我需要 PHP是否为此提供功能? 问题答案: 尝试以下尺寸: 输出: 这实现了以下规则: 以小写字母开头的序列后必须跟小写字母和数字; 以大写字母开头的序列后面可以是: 一个或多个大写字母和数字(后跟字符串的结尾或大写字母,后跟小写字母或数字,即下一个序列的开头);要么 一个或多个小写字母或数字。

  • 怎么把 name 等于选项 3 的合并成一条呢,然后把 value 加起来,比如合并成