gpt4 book ai didi

javascript - 将数组转换为修改后的对象

转载 作者:行者123 更新时间:2023-11-30 14:27:12 25 4
gpt4 key购买 nike

let a = ["CBSE/X-White","HOS/A/A1","FoodHOS/S1",
"CBSE/X-Green","HOS/A/A2","FoodHOS/S1",
"CBSE/IX-White","HOS/B/B1","FoodHOS/S1","TRP/T1"]

我正在尝试将“a”的以上值转换为以下 OBJECT 我们可以观察到它也是唯一值。

The output Should be like below After Converting

 {
"CBSE":[
"X-WHITE",
"X-Green",
"IX-White"
],
"HOS":{
"A":[
"A1",
"A2"
],
"B":[
"B1"
]
},
"FoodHOS":[
"S1",
"S2"
],
"TRP":[
"T1"
]
}

我尝试过的:

我使用此代码将“a”转换为以下形式

 const munge = a =>
a.reduce((res, e) => {
e = e.split("/");
let a = {};
let previousKey = e.shift();
res[previousKey] = a;
let root = res;
while (e.length) {
const newKey = e.shift();

if(e.length == 0){
let b = [];
b.push(newKey);
root[previousKey] = b;
}
else
a[newKey] = {};

if (e.length) {
root = a;
a= a[newKey];
}
previousKey = newKey;
}

return res;
}, {});
console.log(JSON.stringify(munge(a)));

{
"CBSE":[
"IX-White"
],
"HOS":{
"B":[
"B1"
]
},
"FoodHOS":[
"S1"
],
"TRP":[
"T1"
]
}

实际上我正在尝试制作一个支持 Angular 树组件的对象使用我的数据结构,我想转换为 Angular Tree Comp 数据输入,

https://material.angular.io/components/tree/overview

https://stackblitz.com/angular/jamlvojaqjeg?file=app%2Ftree-checklist-example.ts

最佳答案

According to the angular's material tree component, this below code will work. What I have done is modified your code and added a check for the existing object.

let a = ["CBSE/sdfsf/X-White", "HOS/A/AA/A1", "FoodHOS/S1", "CBSE/X-Green", "HOS/A/A2",
"FoodHOS/S1", "CBSE/IX-White", "HOS/A/B1", "FoodHOS/S1", "TRP/T1"]

// const isEmpty = (obj) => {
// return Object.keys(obj).length === 0 && obj.constructor === Object;
// }


const munge = a =>
a.reduce((res, e) => {
e = e.split("/");
let a = {};
let previousKey = e.shift();
if (res[previousKey]) {
a = res[previousKey];
} else {
res[previousKey] = a;
}
let root = res;
while (e.length) {
const newKey = e.shift();

if (e.length == 0) {
let b = [];
if (root[previousKey] instanceof Array) {
b = root[previousKey];
} else if (Object.keys(root[previousKey]).length) {
b = root[previousKey];
}
if (b instanceof Array) {
if (!b.includes(newKey))
b.push(newKey);
root[previousKey] = b;
} else {
root[previousKey][newKey] = null;
}
}
else {
if (!a[newKey]) {
a[newKey] = {};
}
}

if (e.length) {
root = a;
a = a[newKey];
}
previousKey = newKey;
}

return res;
}, {});

console.log(JSON.stringify(munge(a)));

关于javascript - 将数组转换为修改后的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51745983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com