如何从嵌套引用中展平我的数据?

我需要一些帮助来构建一些数据,但我需要一些见解来尽可能提高性能。我一直在用递归和多个循环失去理智。我已经简化了数据以理解这个概念,并根据您的见解自行解决。我有:


const data = [

{

   id: 'W1', 

   color: red,

   personId: 'P77',

},

{

   id: 'W7', 

   color: yellow,

   personId: 'P21',

},

]


const persons = [

{

   id: 'P77',

   name: 'Peter',

   favoriteFoodId: 'FF4',

},

{

   id: 'P21',

   name: 'John',

   favoriteFood: 'FF9',

}

];


const favoriteFood = [

{

   id: 'FF9'

   food: 'pasta'

  description: 'fresh italian pasta from stone oven'

},

{

   id: 'FF4'

   food: 'banana'

  description: 'fresh bananas from the tree'

}

]

如何合并数据以与其所有引用平展?我如何使这个足够通用以处理深度嵌套以压平它并获取引用?我试过这个,但我只是循环太多,它看起来不再正常了。


我想得到这样的结果:


const result  = [

{

   id: 'W1', 

   color: red,

   name: 'Peter',

  food: 'banana'

  description: 'fresh bananas from the tree'

},

{

   id: 'W7', 

   color: yellow,

   name: 'Peter',

    food: 'pasta'

   description: 'fresh italian pasta from stone oven'

},

]

并且result将被传递给我的表格组件,将呈现每个对象的行


子衿沉夜
浏览 107回答 1
1回答

慕侠2389804

你考虑过字典吗?const data =&nbsp;{&nbsp; &nbsp;'W1':{ color: "red" ,&nbsp; personId: 'P77' }&nbsp; &nbsp;,'W7':{ color: "yellow", personId: 'P21'},}const persons ={&nbsp; 'P77':{ name: 'Peter', favoriteFoodId: 'FF4' },&nbsp; &nbsp;'P21':{ name: 'John', favoriteFoodId: 'FF9' }&nbsp;}const favoriteFoods =&nbsp;{&nbsp; &nbsp;'FF9':{ food: 'pasta', description: 'fresh italian pasta from stone oven' }&nbsp; ,'FF4':{ food: 'banana', description: 'fresh bananas from the tree' }}function getFavFood( pId , field ){&nbsp; return favoriteFoods[ persons[ data[pId].personId ].favoriteFoodId ][field]}// not sure what template library you'll be using// but for now plain old js....table = "<TABLE>"for( d in data){&nbsp; table += `<TR style="background:${data[d].color}">`&nbsp; + `<TD>${ persons[ data[d].personId ].name }</TD>`&nbsp; + `<TD>${ getFavFood( d , "food" ) }</TD>`&nbsp; + `<TD>${ getFavFood( d , "description" ) }</TD>`&nbsp; +`</TR>`&nbsp;}table += "</TABLE>"document.body.insertAdjacentHTML( "beforeend" , table )
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript