How to find item in array of objects
How to find item in array of objects
I have array like this :
array = [
{
id:'ABC',
content: ''XYZ,
people :
[
'User 1',
'User 2'
]
}
{
id:'ABC',
content: ''XYZ,
people :
[
'User 3',
'User 4'
]
}
]
I want to find obj have people = user 3
. Here my code bellow :
people = user 3
array.forEach(function(item, index){
var item = item.reverse().find(item => item.people.indexOf('User 3'));
console.log(item);
});
Because I want get latest obj so I use reverse()
. It's not working ? What can I do now. Thank
reverse()
data
If your want to get the latest item, why do you want to get
user 3
instead of user 4
. By the way, I cannot see any need to use JQuery here.– vahdet
Jun 29 at 9:38
user 3
user 4
6 Answers
6
Try this;
array.forEach(function(item){
if(item.people.indexOf('User 3') > -1);
console.log(item);
});
Here's how you can filter such objects -
let array = [{
id: 'ABC',
content: '',
people: [
'User 1',
'User 2'
]
}, {
id: 'ABC',
content: '',
people: [
'User 3',
'User 4'
]
}];
console.log(array.filter(obj => -1 != obj.people.indexOf("User 3")));
You aren't using the item
or index
argument to the forEach
function (you name some other things item
, but you never use the arguments), so your function is going to do the same thing every iteration.
item
index
forEach
item
var result = array.find( function ( item ) {
return item.people.includes( 'User 3' );
})
result
will be 1 object. If you're looking for all objects with User 3
, use filter
instead of find
.
result
User 3
filter
find
This will give you most recent result.
const arr = [
{
id:'ABC',
content: 'XYZ',
people :
[
'User 1',
'User 2'
]
},
{
id:'ABC',
'content': 'XYZ',
'people' :
[
'User 3',
'User 4'
]
}
]
console.log(arr.filter(item => item.people.includes('User 3')).slice(-1)[0]);
One option is to use filter()
to get all result of the search. Use pop()
to get the last one.
filter()
pop()
let array = [
{"id":"ABC","content":"XYZ","people":["User 1","User 2"]},
{"id":"ABC","content":"XYZ","people":["User 3","User 4"]},
{"id":"XXX","content":"XXX","people":["User 3","User 4"]}
];
let toSearch = 'User 3';
let result = array.filter(o => o.people.includes(toSearch)).pop();
console.log(result);
You can also use Array.find()
method like:
Array.find()
var array = [
{
id:'ABC',
content: 'XYZ',
people :
[
'User 1',
'User 2'
]
},
{
id:'ABC',
content: 'XYZ',
people :
[
'User 3',
'User 4'
]
}
];
var res = array.find(obj => obj.people.indexOf('User 3') !== -1);
console.log(res);
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
what is
data
? i don't see it in your code– Carsten Løvbo Andersen
Jun 29 at 9:38