猿问

迭代对象键并将内部对象的键放入一个数组

我试图将Object.keys所有的键放入一个数组中,但遇到了一些困难。


目前我正在尝试这个,但我得到了每个对象键的数组 Object.keys(myObject).map(x=>Object.keys(myObject[x]))


目的:


    {

   "a1G0R000002Sv15UAC":{

      "a1K0R000000ytEsUAI":{ <---

         "test2_2":"test2"

      }

   },

   "a1G0R000002SvdYUAS":{

      "a1K0R000000yu8EUAQ":{ <---

         "test2_2":"test2"

      },

      "a1K0R000000ytEsUAI":{ <---

         "string_1":"test"

      }

   },

   "a1G0R000002T4NIUA0":{

      "a1K0R000000ytEsUAI":{ <---

         "string_1":"test"

      }

   }

}

所需数组:["a1K0R000000ytEsUAI","a1K0R000000yu8EUAQ","a1K0R000000ytEsUAI","a1K0R000000ytEsUAI"]



当年话下
浏览 103回答 3
3回答

叮当猫咪

您可以使用flat将结果转换为单个数组”const myObject =&nbsp; &nbsp; &nbsp;{&nbsp; &nbsp;"a1G0R000002Sv15UAC":{&nbsp; &nbsp; &nbsp; "a1K0R000000ytEsUAI":{&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"test2_2":"test2"&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;},&nbsp; &nbsp;"a1G0R000002SvdYUAS":{&nbsp; &nbsp; &nbsp; "a1K0R000000yu8EUAQ":{&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"test2_2":"test2"&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; "a1K0R000000ytEsUAI":{&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"string_1":"test"&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;},&nbsp; &nbsp;"a1G0R000002T4NIUA0":{&nbsp; &nbsp; &nbsp; "a1K0R000000ytEsUAI":{&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"string_1":"test"&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}}const keys = Object.keys(myObject).map(key => Object.keys(myObject[key])).flat();console.log(keys)

ITMISS

使用mapObject.entries(myObject).map(x&nbsp;=>&nbsp;Object.keys(x[1])).flat()

收到一只叮咚

您将不得不使用 2 个for..in循环。简单来说,for..in循环遍历对象的键。有关更多信息,您可以查看MDN 文档。const originalObject = {&nbsp; &nbsp;"a1G0R000002Sv15UAC":{&nbsp; &nbsp; &nbsp; "a1K0R000000ytEsUAI":{&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"test2_2":"test2"&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;},&nbsp; &nbsp;"a1G0R000002SvdYUAS":{&nbsp; &nbsp; &nbsp; "a1K0R000000yu8EUAQ":{&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"test2_2":"test2"&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; "a1K0R000000ytEsUAI":{&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"string_1":"test"&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;},&nbsp; &nbsp;"a1G0R000002T4NIUA0":{&nbsp; &nbsp; &nbsp; "a1K0R000000ytEsUAI":{&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"string_1":"test"&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}}const desiredArray = []for (let i in originalObject) {&nbsp; for(let j in originalObject[i]) {&nbsp; &nbsp; desiredArray.push(j)&nbsp; }}console.log(desiredArray)
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答