arr = [['a', 'b', 'c'], ['a', 'e'], ['a', 'f'], ['a', 'b', 'd']]
res = {
"id": "a",
"children": [
{"id": "e", "children": [], "matchneedtags": ['a', 'e']},
{"id": "f", "children": [], "matchneedtags": ['a', 'f']},
{
"id": "b", "children": [
{"id": "c", "children": [], "matchneedtags": ['a', 'b', 'c']},
{"id": "d", "children": [], "matchneedtags": ['a', 'b', 'd']},
],
"matchneedtags": ['a', 'b']},
],
"matchneedtags": ['a']
}将 arr 的数据格式转化为 res
方法一:
var arr= [['a', 'b', 'c'], ['a', 'e'], ['a', 'f'], ['a', 'b', 'd']]
function convertData(arr) {
let res = {};
let root = { "id": "", "children": [] };
res.id = arr[0][0];
res.children = root.children;
res.matchneedtags = [res.id];
for (let i = 1; i < arr.length; i++) {
let currentNode = root;
for (let j = 0; j < arr[i].length; j++) {
let foundChild = currentNode.children.find(child => child.id === arr[i][j]);
if (!foundChild) {
let newChild = {
"id": arr[i][j],
"children": [],
"matchneedtags": [...arr[i].slice(0, j + 1)]
};
currentNode.children.push(newChild);
foundChild = newChild;
}
currentNode = foundChild;
}
}
return JSON.stringify(res, null, 2);
}
console.log(convertData(arr));
方法二:
var arr= [['a', 'b', 'c'], ['a', 'e'], ['a', 'f'], ['a', 'b', 'd']]
function convertToNestedObject(arr) {
let nestedObj = {};
function createNestedObj(obj, ids) {
if (ids.length === 0) {
obj.children = [];
obj.matchneedtags = [];
} else {
let id = ids.shift();
let child = obj.children.find(c => c.id === id);
if (!child) {
child = { id: id, children: [], matchneedtags: [id] };
obj.children.push(child);
}
createNestedObj(child, ids);
}
}
arr.forEach(ids => createNestedObj(nestedObj, ids));
nestedObj.id = nestedObj.matchneedtags[0];
return nestedObj;
}
let res = convertToNestedObject(arr);
console.log(res);
方法三:
var arr= [['a', 'b', 'c'], ['a', 'e'], ['a', 'f'], ['a', 'b', 'd']]
var arr2 = []
var res2 = {}
arr.forEach((item,index)=>{
item.forEach((item2,index2) => {
if(!arr2.includes(item2)){
arr2.push(item2)
}
})
})
var matchneedtags = []
var length = 0
var resId
arr2.forEach((item,index) =>{
var num = 0
arr.forEach((item1,index1)=>{
if(item1.indexOf(item) > -1){
length = item1.length
num++
}
})
console.log(num)
if(num == arr.length){
var matchneedtags1 = []
matchneedtags1.push(item)
matchneedtags.push(item)
res2 ={
"id":item,
"children":[],
"matchneedtags":matchneedtags1
}
}else{
if(num > 1 && num < arr.length){
resId = item
}
if(length == 2 || num > 1 && num < arr.length){
var matchneedtags2 = []
matchneedtags2.push(res2.matchneedtags[0])
matchneedtags2.push(item)
matchneedtags.push(item)
var obj ={
"id":item,
"children":[],
"matchneedtags":matchneedtags2
}
res2.children.push(obj)
} else {
if(length > 2){
res2.children.forEach((item3,index3) =>{
if(item3.id == resId){
var matchneedtags3 = JSON.parse(JSON.stringify(item3.matchneedtags))
matchneedtags3.push(item)
var obj ={
"id":item,
"children":[],
"matchneedtags":matchneedtags3
}
item3.children.push(obj)
}
})
}
}
}
})
console.log(res2)