我想使用es6的查找,我觉得在嵌套循环中检查退出对象真的很有用,但是它有一个问题,有时候对象不存在我可以#&# 39; t链接它以获得我想要的价值。
这是一个例子
https://jsbin.com/waxotajeji/edit?html,js,console,output
const data = [
{
"id": 1,
"name": "Date"
},
{
"id": 2,
"name": "Time"
},
{
"id": 3,
"name": "Shop"
},
{
"id": 4,
"name": "Price"
},
{
"id": 5,
"name": "Token(s)"
},
{
"id": 6,
"name": "Type"
}
]
const sortable = {
"data": [
{
"id": 1,
"sortKey": "created_at"
},
{
"id": 4,
"sortKey": "total_spent"
}
]
}
data.map(o=>{
let sortKey = sortable.data.find(o2=>o2.id===o.id).sortKey
console.log(sortKey)
})
上面的代码没有工作,我可能不得不做sortable.data.find(o2=>o2.id===o.id) && sortable.data.find(o2=>o2.id===o.id).sortKey
我觉得这很难看,有什么解决方法吗?
答案 0 :(得分:0)
您可以将map中的代码声明为函数,并将其保存在不同的文件中,以使代码变为干净。
function findInSortableData(value, index){
let sortKey = {};
if (sortable && sortable.data) {
sortKey = (sortable.data.find(o2 => o2.id === value.id) || {}).sortKey;
}
return sortKey;
}
data.map(findInSortableData);