我想使用es6的发现,我发现它在嵌套循环中的检查对象非常有用,但是有一个问题,有时不存在,我无法链它可以获得我想要的价值。
这是一个示例
https://jsbin.com/waxotajeji/edit?html,js ,,
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
,我认为这很丑陋,对此有任何解决方法吗?
您可以将代码内部映射为函数,并将其保存在其他文件中以使代码作为清洁。
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);