嘿伙计们,我需要一些帮助来构建一些数据,但我需要一些见解才能尽可能提高性能。我一直对递归和多重循环失去了理智。我简化了数据以理解这个概念,并根据您的见解自行解决它。 我有:
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'
},
]
并且结果
将被传递到我的表格组件,该组件将每个对象呈现为一行
最佳答案
你考虑过字典吗?
const data =
{
'W1':{ color: "red" , personId: 'P77' }
,'W7':{ color: "yellow", personId: 'P21'},
}
const persons =
{
'P77':{ name: 'Peter', favoriteFoodId: 'FF4' },
'P21':{ name: 'John', favoriteFoodId: 'FF9' }
}
const favoriteFoods =
{
'FF9':{ food: 'pasta', description: 'fresh italian pasta from stone oven' }
,'FF4':{ food: 'banana', description: 'fresh bananas from the tree' }
}
function getFavFood( pId , field ){
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){
table += `<TR style="background:${data[d].color}">`
+ `<TD>${ persons[ data[d].personId ].name }</TD>`
+ `<TD>${ getFavFood( d , "food" ) }</TD>`
+ `<TD>${ getFavFood( d , "description" ) }</TD>`
+`</TR>`
}
table += "</TABLE>"
document.body.insertAdjacentHTML( "beforeend" , table )
关于javascript - 如何展平嵌套引用中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58538099/