我有一个对象和数组的数组。
如果对象数组中有value property same
-
如果
place
包含数组list
返回第一个obj -
如果
place
相等包含/不包含返回第一个obj
如果没有以上条件返回undefined;使用javascript
var list=['SG','TH','MY']
var arrobj1=[
{id:1, name:'userone',place:'SG', value:100},
{id:2, name:'usertwo',place:'TH', value:100},
{id:3, name:'userthree',place:'IL',value:200},
]
Expected Output
{id:1, name:'userone',place:'SG', value:100}
****
var arrobj2=[
{id:1, name:'userone',place:'IN', value: 200},
{id:2, name:'usertwo',place:'SL',value: 100},
{id:3, name:'userthree',place:'SL', value: 100},
]
Expected Output
{id:2, name:'usertwo',place:'SL',value: 100}
****
var arrobj3=[
{id:1, name:'userone',place:'SL', value:10},
{id:2, name:'usertwo',place:'IN', value:20},
{id:3, name:'userthree',place:'KL', value:30},
]
Expected Output
undefined
尝试
var result= arrobj.find(e=>{
if((e.value === e.value) && (list.includes(e.place)){
return e
}
})
我已经添加了内联注释来满足需求。在某些情况下,我不是很确定你的意思,所以如果你澄清问题,我可以调整答案
var list = ['SG', 'TH', 'MY']
var arrobj1 = [{
id: 1,
name: 'userone',
place: 'SG',
value: 100
},
{
id: 2,
name: 'usertwo',
place: 'TH',
value: 100
},
{
id: 3,
name: 'userthree',
place: 'IL',
value: 200
},
]
//Expected Output
//{id:1, name:'userone',place:'SG', value:100}
//****
var arrobj2 = [{
id: 1,
name: 'userone',
place: 'IN',
value: 200
},
{
id: 2,
name: 'usertwo',
place: 'SL',
value: 100
},
{
id: 3,
name: 'userthree',
place: 'SL',
value: 100
},
]
//Expected Output
//{id:2, name:'usertwo',place:'SL',value: 100}
//****
var arrobj3 = [{
id: 1,
name: 'userone',
place: 'SL',
value: 10
},
{
id: 2,
name: 'usertwo',
place: 'IN',
value: 20
},
{
id: 3,
name: 'userthree',
place: 'KL',
value: 30
},
]
//Expected Output
//undefined
function getMatch(places, arrObj) {
// .find will return the first item that matches the condition provided
return arrObj.find(
l => list.includes(l.place) // either the place of this item must exist in the list
|| arrObj.filter(arr => arr.value === l.value).length > 1) // or the value of this item must appear more than once in the list
}
console.log(getMatch(list, arrobj1));
console.log(getMatch(list, arrobj2));
console.log(getMatch(list, arrobj3));