通过给定索引解析具有嵌套对象的数组,获取其名称

链接到沙盒:https://codesandbox.io/s/cool-northcutt-7c9sr


我有一个带家具的目录,我需要制作动态面包屑。有一个数组,其中包含 5 层深的嵌套对象。当我渲染家具列表时,我会保存此列表数组中的所有索引。


预期输出:使用我的索引,我需要解析具有嵌套数组的对象,获取属于该索引的每个对象的名称并将其保存在数组中


用户单击清单时保存的索引。键是对象名称,属性是实际索引。


menuIndexes : {

  buildings: 0,

  building_styles: 3,

  rooms: 2,

  room_fillings: 0,

  filling_types: 1,

}

那段数据,我从家具列表渲染。名称属性是菜单中链接的名称


{

  buildings: [

    {

      name: 'office',

      building_styles: [

        {

          name: 'interior',

          rooms: [

            {

              name: 'open space',

              filling_types: [

                {

                  name: 'furniture',

                  room_fillings: [

                    {

                      name: 'items',

                       // rendering inventories

                      inventories: [


                        {

                          id: 1,

                          name: 'tv'

                        },

                        {

                          id: 2,

                          name: 'chair'

                        },

                        {

                          id: 3,

                          name: 'table'

                        },

                      ]

                    }

                  ]


                }

              ]

            }

          ]

        },

      ]

    },

  ]

}

此图像用于了解我在哪里获得此保存的索引

http://img3.mukewang.com/632d6eb90001588411050893.jpg

我试图制作递归函数,但它只得到第一个数组,不会进一步进入嵌套数组


  const displayBreadCrumbs = () => {

    let menuKeys = Object.keys(menuIndexes)

    console.log({ menuIndexes });

    console.log(file);

    let arr = []

    let i = 0

    let pathToParse = file



    if (i < menuKeys.length) {

      if (menuKeys[i] in pathToParse) {

        pathToParse = pathToParse[menuKeys[i]][menuIndexes[menuKeys[i]]]

        console.log('pathToParse', pathToParse);

        i = i + 1

        // displayBreadCrumbs()

      }

    }

  }


繁星点点滴滴
浏览 78回答 3
3回答

喵喵时光机

您可以遍历 中的每个键值对对象,以查看哪个键属于当前对象。获得适用于当前对象的键后,您可以访问其关联的数组以及需要查看的索引。找到键值对后,可以从条目中删除键值对,然后再次以递归方式查找新对象中的下一个键。您可以继续此操作,直到找不到属于当前对象的键(即:findIndex返回-1);menuIndexespathToParsemenuIndexesdataconst pathToParse = { buildings: [ { name: 'office', building_styles: [ { name: 'interior', rooms: [ { name: 'open space', filling_types: [ { name: 'furniture', inventories: [{ id: 1, name: 'tv' }, { id: 2, name: 'chair' }, { id: 3, name: 'table' }, ] } ] } ] }, ] }, ] }const menuIndexes = {&nbsp; buildings: 0,&nbsp; building_styles: 0,&nbsp; rooms: 0,&nbsp; room_fillings: 0,&nbsp; filling_types: 0,}function getPath(data, entries) {&nbsp; const keyIdx = entries.findIndex(([key]) => key in data);&nbsp; if(keyIdx <= -1)&nbsp; &nbsp; return [];&nbsp; &nbsp;&nbsp;&nbsp; const [objKey, arrIdx] = entries[keyIdx];&nbsp; const obj = data[objKey][arrIdx];&nbsp; entries.splice(keyIdx, 1);&nbsp; return [obj.name].concat(getPath(obj, entries));&nbsp;}console.log(getPath(pathToParse, Object.entries(menuIndexes)));的用途是搜索对象以查找要查看的键(因为我们不想依赖于对象的键排序)。如果您对 有更多的控制权,则可以将其存储在一个数组中,您可以在其中安全地依赖元素的顺序,从而依赖键:Object.entries()datamenuIndexesmenuIndexesconst pathToParse = { buildings: [ { name: 'office', building_styles: [ { name: 'interior', rooms: [ { name: 'open space', filling_types: [ { name: 'furniture', inventories: [{ id: 1, name: 'tv' }, { id: 2, name: 'chair' }, { id: 3, name: 'table' }, ] } ] } ] }, ] }, ] };const menuIndexes = [{key: 'buildings', index: 0}, {key: 'building_styles', index: 0}, {key: 'rooms', index: 0}, {key: 'filling_types', index: 0}, {key: 'inventories', index: 0}, ];function getPath(data, [{key, index}={}, ...rest]) {&nbsp; if(!key)&nbsp; &nbsp; return [];&nbsp; const obj = data[key][index];&nbsp; return [obj.name, ...getPath(obj, rest)];&nbsp;}console.log(getPath(pathToParse, menuIndexes));

慕神8447489

像往常一样,我会在一些可重用的部件上构建这样的函数。这是我的方法:// Utility functionsconst path = (obj, names) =>&nbsp; names .reduce ((o, n) => (o || {}) [n], obj)const scan = (fn, init, xs) =>&nbsp;&nbsp; xs .reduce (&nbsp; &nbsp; (a, x, _, __, n = fn (a .slice (-1) [0], x)) => [...a, n],&nbsp;&nbsp; &nbsp; [init]&nbsp; ) .slice (1)&nbsp;&nbsp;const pluck = (name) => (xs) =>&nbsp; xs .map (x => x [name])// Main functionconst getBreadCrumbs = (data, indices) =>&nbsp;&nbsp; pluck ('name') (scan (path, data, Object .entries (indices)))// Sample dataconst data = {buildings: [{name: "office", building_styles: [{building_style: 0}, {building_style: 1}, {building_style: 2}, {name: "interior", rooms: [{room: 0}, {room: 1}, {name: "open space", filling_types: [{filling_type: 0}, {name: "furniture", room_fillings: [{name: "items", inventories: [{id: 1, name: "tv"}, {id: 2, name: "chair"}, {id: 3, name: "table"}]}, {room_filling: 1}]}, {filling_type: 2}]}, {room: 3}]}, {building_style: 4}]}]}const menuIndexes = {buildings: 0, building_styles: 3, rooms: 2, filling_types: 1, room_fillings: 0}// Democonsole .log (getBreadCrumbs (data, menuIndexes))我们这里有三个可重用的函数:path&nbsp;采用一个对象和节点名称(字符串或整数)列表,并在给定路径处返回值,或者如果缺少任何节点,则返回值。1&nbsp;例如:undefinedpath&nbsp;({a:&nbsp;{b:&nbsp;[{c:&nbsp;10},&nbsp;{c:&nbsp;20},&nbsp;{c:&nbsp;30},&nbsp;{c:&nbsp;40}]}},&nbsp;['a',&nbsp;'b',&nbsp;2,&nbsp;'c'])&nbsp;//=>&nbsp;30.scan&nbsp;与 非常相似,不同之处在于它不返回最终值,而是返回在每个步骤中计算的值的列表。例如,如果 是 ,则:Array.prototype.reduceadd(x, y) => x + yscan&nbsp;(add,&nbsp;0,&nbsp;[1,&nbsp;2,&nbsp;3,&nbsp;4,&nbsp;5])&nbsp;//=>&nbsp;[1,&nbsp;3,&nbsp;6,&nbsp;10,&nbsp;15]拔出将命名属性从每个对象列表中拉出:pluck&nbsp;('b')&nbsp;([{a:&nbsp;1,&nbsp;b:&nbsp;2,&nbsp;c:&nbsp;3},&nbsp;{a:&nbsp;10,&nbsp;b:&nbsp;20,&nbsp;c:&nbsp;30},&nbsp;{a:&nbsp;100,&nbsp;b:&nbsp;200,&nbsp;c:&nbsp;300}])&nbsp; //=>&nbsp;[2,&nbsp;20,&nbsp;200]在实践中,我实际上会进一步考虑这些帮助器,根据 定义来定义,并在定义中使用和。但这对这个问题并不重要。pathconst prop = (obj, name) => (obj || {}) [name]const last = xs => xs.slice (-1) [0]const tail = (xs) => xs .slice (-1)scan然后,我们的 main 函数可以简单地使用这些条目以及&nbsp;2,首先从索引中获取条目,将该条目、我们的函数和数据传递给相关对象节点的列表,然后将结果与我们要提取的字符串一起传递给。Object.entriespathscanpluck'name'我几乎每天都使用。 不太常见,但它足够重要,它被包含在我通常的实用程序库中。有了这样的功能,编写类似 的东西就非常简单了。pathpluckscangetBreadCrumbs1&nbsp;旁注,我通常将其定义为,我发现这是最常用的。此表单恰好更适合所使用的代码,但是将代码调整为我的首选形式很容易:而不是 ,我们可以只编写(names) => (obj) => ...scan (path, data, ...)scan ((a, ns) => path (ns) (a), data, ...)2&nbsp;正如尼克·帕森斯(Nick Parsons)的回答和感谢的评论所指出的那样,将此信息存储在一个显式排序的数组中是有一个很好的论据,而不是依赖于一般对象获得的奇怪和任意的顺序。如果这样做,则此代码只能通过删除 main 函数中的调用来更改。Object .entries

慕斯709654

您可以像这样定义一个递归函数,它循环访问键并在数据中找到相应的对象。找到数据后,它会将名称推送到输出数组中,并使用此对象再次调用该函数,并且menuIndexesmenuIndexesconst displayBreadCrumbs = (data, menuIndexes) => {&nbsp; &nbsp; const output = [];&nbsp; &nbsp; Object.keys(menuIndexes).forEach(key => {&nbsp; &nbsp; &nbsp; &nbsp; if (data[key] && Array.isArray(data[key]) && data[key][menuIndexes[key]]) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output.push(data[key][menuIndexes[key]].name);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output.push(...displayBreadCrumbs(data[key][menuIndexes[key]], menuIndexes));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; return output;};const data = { buildings: [ { name: 'office', building_styles: [ { name: 'interior', rooms: [ { name: 'open space', filling_types: [ { name: 'furniture', inventories: [{ id: 1, name: 'tv' }, { id: 2, name: 'chair' }, { id: 3, name: 'table' }, ] } ] } ] }, ] }, ] };const menuIndexes = {&nbsp; buildings: 0,&nbsp; building_styles: 0,&nbsp; rooms: 0,&nbsp; room_fillings: 0,&nbsp; filling_types: 0,};displayBreadCrumbs(data, menuIndexes); // ["office", "interior", "open space", "furniture"]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript