How do I find a particular value in an array?
newdata
(2) [{…}, {…}]
0: {city: 'mytown', photo: 'data:image/png;base64,iVBORw0AAJoA…FLhAXTkSuQmCC', state: 'YO', suite: 'Penthouse suite', zip_code: '54321', …}
1: {city: 'yourtown', state: 'MO', zip_code: '12345', last_name: 'Dtest2', cell_phone: '4082789949', …}length: 2[[Prototype]]: Array(0)
newdata.indexOf("12345")
-1
newdata.includes("12345")
false
baffled: looking for the index that holds a value – do I need to index through all the keys individually?
Bruce Merritt is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
5
The value you’re looking for is a property of one of the objects within the array, not a value in the array itself. This is why it’s not working.
To do what you required I’d suggest using filter()
instead, and checking if any value of the object within the array contains the value you’re looking for. Here’s a working example of that:
const newdata = [{ city: 'mytown', state: 'YO', suite: 'Penthouse suite', zip_code: '54321'}, { city: 'yourtown', state: 'MO', zip_code: '12345', last_name: 'Dtest2', cell_phone: '4082789949' }]
const searchTerm = '12345';
const filteredData = newdata.filter(obj => Object.values(obj).includes(searchTerm));
console.log(filteredData);