簡體   English   中英

從嵌套的對象數組中獲取鍵

[英]get keys from the nested array of objects

我正在尋找一個可以改變我的數據的函數,即帶有嵌套對象的對象數組。 它將包括具有對象/數組值的鍵(它應該只包括具有直接字符串/數字/布爾值的鍵)。

例子

[
{
  id: 1,
  person1: {
    firstname: "test1",
    lastname: 'singh',
    address: {
        state: "maharashtra",
    }
  }
},
{
  id: 2,
  person2: {
    firstname: "test2",
    lastname: 'rathod',
    address: {
        state: "kerala",
    }
  }
},
{
  id: 3, 
  person3: {
    firstname: "test3",
    lastname: 'gokale',
    address: {
        state: "Tamilnadu",
    }
  }
}

]

預期產出

[
{
  title: 'person1',
  value: 'person.id'
},
{
    title: 'person1',
    value: 'person.firstname'
},
{
    title: 'person1',
    value: 'person.lastname'
},
{
    title: 'person1',
    value: 'person.address'
},
{
    title: 'person1',
    value: 'person.address.state'
},
...sameforOthers

]

基本上,我需要一個函數來獲取一個數組並返回一個對象數組,如上面給出的預期輸出

提前致謝

我想出了一個解決方案。 以下是https://codesandbox.io/s/heuristic-rubin-yy2cyy?file=/src/index.js:0-213same的代碼沙箱鏈接

 const suggestions = [
      {
        id: 1,
        person1: {
          id: "1",
          firstname: "test1",
          lastname: "singh",
          address: {
            state: "maharashtra"
          },
          attributeId: "fhgfgh"
        }
      }
    ];

const typeList = ["string", "number", "boolean"];

const getLabelValue = (itemList, initalArr, parentId) => {
  if (Array.isArray(itemList)) {
    itemList.forEach((currentItem, idx) => {
      const id = parentId ? `${parentId}.${idx}` : idx;
      if (typeList.includes(typeof currentItem)) {
        initalArr.push({
          title: id,
          value: id
        });
      } else {
        getLabelValue(currentItem, initalArr, id);
      }
    });
  } else {
    let keys = Object.keys(itemList);
    keys.forEach((currentKey) => {
      let currentItem = itemList[currentKey];
      const id = parentId ? `${parentId}.${currentKey}` : currentKey;
      if (typeList.includes(typeof currentItem)) {
        initalArr.push({
          title: id,
          value: id
        });
      } else {
        getLabelValue(currentItem, initalArr, id);
      }
    });
  }
  return initalArr;
};

console.log(">>>>>>>>>", getLabelValue(suggestions, [], ""));

像這樣的東西?

[
{
  id: 1,
  person1: {
    firstname: "test1",
    lastname: 'singh',
    address: {
        state: "maharashtra",
    }
  }
},
{
  id: 2,
  person2: {
    firstname: "test2",
    lastname: 'rathod',
    address: {
        state: "kerala",
    }
  }
},
{
  id: 3, 
  person3: {
    firstname: "test3",
    lastname: 'gokale',
    address: {
        state: "Tamilnadu",
    }
  }
}
].map(item => {
    return {
        id: item.id,
        title: Object.keys(item)[1],
        value: item[Object.keys(item)[1]]
    }
})

暫無
暫無

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

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