[英]how to retrieve the object from array of objects and arrays using javascript
I have array of objects and arrays.我有对象数组和 arrays。
If the array of objects has value property same
如果对象数组具有
value property same
and if place
includes of arrraylist list
return first obj如果
place
包括 arrraylist list
返回第一个 obj
and if place
is equal includes/not includes return first obj如果
place
相等,则包含/不包含返回第一个 obj
if no above conditions return undefined;如果没有以上条件则返回undefined; using javascript
使用 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
Tried尝试过
var result= arrobj.find(e=>{
if((e.value === e.value) && (list.includes(e.place)){
return e
}
})
I've added inline comments to correspond to the requirements.我已经添加了内联注释以符合要求。 I wasn't sure exactly what you meant in some cases, so I can adjust the answer if you clarify the question
在某些情况下我不确定你的意思,所以如果你澄清问题我可以调整答案
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.