簡體   English   中英

如何從 object 的嵌套數組中獲取每個父項的值

[英]How to get the value of each parent from a nested array of object

所以我有一個 object 的多個數組,每個 object 我都包含一個孩子。

例如

const data = [
    {
        id: 1,
        name: 'parent 1',
        children: [
            {
                id: 'c1',
                name: 'child 1',
                children: [
                    {
                        id: 'g1',
                        name: 'grand 1',
                        children: [],
                    },
                ],
            },
        ],
    },
    {
        id: 2,
        name: 'parent 2',
        children: [
            {
                id: 2,
                name: 'c1',
                children: [],
            },
        ],
    },
    { id: 3, name: 'parent 3', children: [] },
];

我想要發生的是,如果我正在搜索的 ID 是“g1”,我會得到結果

const result = ['parent 1', 'c1', 'grand 1']

循環只會停止並獲取它經過的所有名稱,直到滿足條件(在本例中為 id)

當前方法完成

/**
 * Details
 * @param id the value you are searching for
 * @param items nested array of object that has child
 * @param key name of the value you are looking for
 * @returns string of array that matches the id
 * @example ['parent 1', 'c1', 'grand 1']
 */
export function findAll(id: string, items: any, key: string): string[] {
  let i = 0;
  let found;
  let result = [];

  for (; i < items.length; i++) {
    if (items[i].id === id) {
      result.push(items[i][key]);
    } else if (_.isArray(items[i].children)) {
      found = findAll(id, items[i].children, key);
      if (found.length) {
        result = result.concat(found);
      }
    }
  }
  return result;
}

下面的解決方案是執行搜索的遞歸函數。

 const data = [ { id: 1, name: 'parent 1', children: [ { id: 'c1', name: 'child 1', children: [ { id: 'g1', name: 'grand 1', children: [], }, ], }, ], }, { id: 2, name: 'parent 2', children: [ { id: 2, name: 'c1', }, ], }, { id: 3, name: 'parent 3', children: [{}] }, ]; function getPath(object, search) { if (object.id === search) return [object.name]; else if ((object.children) || Array.isArray(object)) { let children = Array.isArray(object) ? object : object.children; for (let child of children) { let result = getPath(child, search); if (result) { if (object.id )result.unshift(object.name); return result; } } } } //const result = ['parent 1', 'c1', 'grand 1'] const result = getPath(data, 'g1'); console.log(result);

我編寫了這段迭代代碼,可能會對您有所幫助。 它基本上遍歷存儲從頂級到所需 id 的路徑的結構:

function getPath(obj, id) {
    // We need to store path
    // Start stack with root nodes
    let stack = obj.map(item => ({path: [item.name], currObj: item}));
    while (stack.length) {
        const {path, currObj} = stack.pop()
        if (currObj.id === id) {
            return path;
        } else if (currObj.children?.length) {
            stack = stack.concat(currObj.children.map(item => ({path: path.concat(item.name), currObj: item})));
        }
    }
    return null; // if id does not exists
}

此代碼假定您的結構是正確的並且沒有遺漏任何部分(除了可以為空的子項)。 Btw,你的回答正確嗎? 我猜路徑應該是: ["parent 1", "child 1", "grand 1"]

您可以編寫一個遞歸函數,在該函數中,您在將遍歷的對象累積到堆棧中時遍歷數組。 一旦你得到一個你想要的 id (id == g1)的對象,你就可以打印解決方案。 它可能是這樣的:

'use strict';

function print(stack) {
    //console.log("Printing result...\n");
    let result = "";
    stack.forEach(element => {
        result += element["name"] + " > ";
    });
    console.log(result + "\n");
}

function walkThrough(data, id, stack) {
    if (data !== undefined)
    for (let i = 0; i < data.length; i++) {
        const element = data[i];
        //console.log("Going through " + element["name"] + " with id == " + element["id"]);
        stack.push(element);
        if (element["id"] == id) print(stack);
        else walkThrough(element["children"], id, stack);            
    }
}

const data = [
    {
        "id": 1,
        "name": 'parent 1',
        "children": [
            {
                "id": 'c1',
                "name": 'child 1',
                "children": [
                    {
                        "id": 'g1',
                        "name": 'grand 1',
                        "children": [],
                    },
                ],
            },
        ],
    },
    {
        "id": 2,
        "name": 'parent 2',
        "children": [
            {
                "id": 2,
                "name": 'c1',
            },
        ],
    },
    { "id": 3, "name": 'parent 3', "children": [{}] },
];
//Calling the function to walk through the array...
walkThrough(data, 'g1', []);

另一種方法(不像上面的解決方案那么優雅,但它也有效)

非常直接:
使用for循環向下迭代到第 3 層,當在第 3 層找到孫子時, break以逃避所有 3 層。

我很好奇不同的解決方案如何比較大型數據集的性能(假設有一百萬條記錄)。

 let i=0, k=0, l=0; let childrenLength = 0, grandChildrenLength = 0; let result = []; let foundGrandChild = false; function searchGrandChild(searchString) { for (i; i< data.length; ++i) { if(data.length > 0){ childrenLength = data[i].children.length; if(childrenLength > 0) { for (k; k < childrenLength; ++k) { if(data[i].children[k] != undefined) { grandChildrenLength = data[i].children[k].children.length; if(grandChildrenLength > 0) { for (l; l < grandChildrenLength; ++l) { if(data[i].children[k].children[l] != undefined) { if(data[i].children[k].children[l].id === searchString) { result.push(data[i].name); result.push(data[i].children[k].id); result.push(data[i].children[k].children[l].name); foundGrandChild = true; console.log('Yap, we found your grandchild 😊') console.log(result); break; } } if(foundGrandChild) break; } } } if(foundGrandChild) break; } } } if(foundGrandChild) break; } if(!foundGrandChild) console.log('sorry, we could not find your grandchild 😮') }; const data = [ { id: 1, name: 'parent 1', children: [ { id: 'c1', name: 'child 1', children: [ { id: 'g1', name: 'grand 1', children: [], }, ], }, ], }, { id: 2, name: 'parent 2', children: [ { id: 2, name: 'c1', }, ], }, { id: 3, name: 'parent 3', children: [{}] }, ]; console.log('Let us search for "g1" ...'); searchGrandChild('g1'); console.log('Let us now search for "g2" ...'); foundGrandChild = false; searchGrandChild('g2');

const arr = [
  { id: "1234", parent_id: "", name: "jakson" },
  { id: "4567", parent_id: "1234", name: "obama" },
  { id: "7891", parent_id: "", name: "twinkel" },
  { id: "9876", parent_id: "1234", name: "behara" },
  { id: "1357", parent_id: "7891", name: "aaraku" },
  { id: "6789", parent_id: "7891", name: "mikel" },
  { id: "7892", parent_id: "4567", name: "aaraku" },
  { id: "8765", parent_id: "4567", name: "mikel" },
  { id: "9108", parent_id: "1234", name: "akshra" },
];
const generateChild = (arr) => {
  return arr.reduce((acc, val, ind, array) => {
    const childs = [];
    array.forEach((el) => {
      if (el.parent_id === val.id) {
        childs.push({ id: el.id, name: el.name, parent_id: el.parent_id });
      }
    });
    return acc.concat({ ...val, childs });
  }, []);
};
console.log(generateChild(arr));

output:
(9) [{...}, {...}, {...}, {...}, {...}, ...]
0
:
(4) {id: "1234", parent_id: "", name: "j...}
1
:
(4) {id: "4567", parent_id: "1234", name...}
2
:
(4) {id: "7891", parent_id: "", name: "t...}
3
:
(4) {id: "9876", parent_id: "1234", name...}
4
:
(4) {id: "1357", parent_id: "7891", name...}
5
:
(4) {id: "6789", parent_id: "7891", name...}
6
:
(4) {id: "7892", parent_id: "4567", name...}
7
:
(4) {id: "8765", parent_id: "4567", name...}
8`enter code here`
:
(4) {id: "9108", parent_id: "1234", name...}
const arr = [
  { id: "1234", parent_id: "", name: "jakson" },
  { id: "4567", parent_id: "1234", name: "obama" },
  { id: "7891", parent_id: "", name: "twinkel" },
  { id: "9876", parent_id: "1234", name: "behara" },
  { id: "1357", parent_id: "7891", name: "aaraku" },
  { id: "6789", parent_id: "7891", name: "mikel" },
  { id: "7892", parent_id: "1234", name: "aaraku" },
  { id: "8765", parent_id: "1234", name: "aaraku" },
  { id: "9108", parent_id: "7891", name: "akshra" },
];

let data = [];
let test = [];
for (i = 0; i < arr.length; i++) {
  if (!test.includes(i)) {
    let x = arr[i];
    for (j = i + 1; j < arr.length; j++) {
      if (
        arr[j].name === arr[i].name &&
        arr[j].parent_id === arr[i].parent_id
      ) {
        Object.assign(x, arr[j]);
        test.push(j);
      }
    }
    data.push(x);
  }
}
console.log(data);
var parentChild = [];
for (i = 0; i < data.length; i++) {
  if (data[i].parent_id === "") {
    parentChild.push(data[i]);
  }
}

for (i = 0; i < data.length; i++) {
  for (j = 0; j < parentChild.length; j++) {
    if (data[i].parent_id === parentChild[j].id) {
      if (parentChild[j].child === undefined) {
        Object.assign(parentChild[j], {
          child: [],
        });
        parentChild[j].child.push(data[i]);
      } else {
        parentChild[j].child.push(data[i]);
      }
    }
  }
}
console.log(parentChild);

output:

(8) [{...}, {...}, {...}, {...}, {...}, ...]
0
:
(4) {id: "1234", parent_id: "", name: "j...}
id
:
"1234"
parent_id
:
""
name
:
"jakson"
child
:
(3) [{...}, {...}, {...}]
0
:
(3) {id: "4567", parent_id: "1234", name...}
id
:
"4567"
parent_id
:
"1234"
name
:
"obama"
1
:
(3) {id: "9876", parent_id: "1234", name...}
id
:
"9876"
parent_id
:
"1234"
name
:
"behara"
2
:
(3) {id: "8765", parent_id: "1234", name...}
id
:
"8765"
parent_id
:
"1234"
name
:
"aaraku"
1
:
(3) {id: "4567", parent_id: "1234", name...}
id
:
"4567"
parent_id
:
"1234"
name
:
"obama"
2
:
(4) {id: "7891", parent_id: "", name: "t...}
id
:
"7891"
parent_id
:
""
name
:
"twinkel"
child
:
(3) [{...}, {...}, {...}]
0
:
(3) {id: "1357", parent_id: "7891", name...}
id
:
"1357"
parent_id
:
"7891"
name
:
"aaraku"
1
:
(3) {id: "6789", parent_id: "7891", name...}
id
:
"6789"
parent_id
:
"7891"
name
:
"mikel"
2
:
(3) {id: "9108", parent_id: "7891", name...}
id
:
"9108"
parent_id
:
"7891"
name
:
"akshra"
3
:
(3) {id: "9876", parent_id: "1234", name...}
id
:
"9876"
parent_id
:
"1234"
name
:
"behara"
4
:
(3) {id: "1357", parent_id: "7891", name...}
id
:
"1357"
parent_id
:
"7891"
name
:
"aaraku"
5
:
(3) {id: "6789", parent_id: "7891", name...}
id
:
"6789"
parent_id
:
"7891"
name
:
"mikel"
6
:
(3) {id: "8765", parent_id: "1234", name...}
id
:
"8765"
parent_id
:
"1234"
name
:
"aaraku"
7
:
(3) {id: "9108", parent_id: "7891", name...}
id
:
"9108"
parent_id
:
"7891"
name
:
"akshra"
(2) [{...}, {...}]
0
:
(4) {id: "1234", parent_id: "", name: "j...}
id
:
"1234"
parent_id
:
""
name
:
"jakson"
child
:
(3) [{...}, {...}, {...}]
0
:
(3) {id: "4567", parent_id: "1234", name...}
id
:
"4567"
parent_id
:
"1234"
name
:
"obama"
1
:
(3) {id: "9876", parent_id: "1234", name...}
id
:
"9876"
parent_id
:
"1234"
name
:
"behara"
2
:
(3) {id: "8765", parent_id: "1234", name...}
id
:
"8765"
parent_id
:
"1234"
name
:
"aaraku"
1
:
(4) {id: "7891", parent_id: "", name: "t...}
id
:
"7891"
parent_id
:
""
name
:
"twinkel"
child
:
(3) [{...}, {...}, {...}]
const arr = [
  { id: "1234", parent_id: "", name: "jakson" },
  { id: "4567", parent_id: "1234", name: "obama" },
  { id: "7891", parent_id: "", name: "twinkel" },
  { id: "9876", parent_id: "1234", name: "behara" },
  { id: "1357", parent_id: "7891", name: "aaraku" },
  { id: "6789", parent_id: "7891", name: "mikel" },
  { id: "7892", parent_id: `enter code here`"4567", name: "aaraku" },
  { id: "8765", parent_id: "4567", name: "mikel" },
  { id: "9108", parent_id: "1234", name: "akshra" },
];
const generateChild = (arr) => {
  return arr.reduce((acc, val, ind, array) => {
    const childs = [];
    array.forEach((el) => {
      if (el.parent_id === val.id) {
        childs.push({ id: el.id, name: el.name, parent_id: el.parent_id });
      }
    });
    return acc.concat({ ...val, childs });
  }, []);
};
console.log(generateChild(arr));

output:
(9) [{...}, {...}, {...}, {...}, {...}, ...]
0
:
(4) {id: "1234", parent_id: "", name: "j...}
1
:
(4) {id: "4567", parent_id: "1234", name...}
2
:
(4) {id: "7891", parent_id: "", name: "t...}
3
:
(4) {id: "9876", parent_id: "1234", name...}
4
:
(4) {id: "1357", parent_id: "7891", name...}
5
:
(4) {id: "6789", parent_id: "7891", name...}
6
:
(4) {id: "7892", parent_id: "4567", name...}
7
:
(4) {id: "8765", parent_id: "4567", name...}
8`enter code here`
:
(4) {id: "9108", parent_id: "1234", name...}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM