0

I have several objects and i would like to get one and check a specific property

so i have

 data: [{is_guest: true},{permission:'is_allowed_ip'}]

Now when i check the console.log(route.data) am getting

0:{is_guest:true},
1:{permission:'is_allowed_ip' }

and typeof route.data is an object

now i would like to get the object with is_guest:true

So i have tried

   const data = Object.keys(route.data).map((index) => {
      if (route.data[index].is_guest) {
       return route.data[index]
      }
    });

  console.log("route data is",data)  //this still returns all the items

But the above fails returning all the objects. How do i loop through all the objects and retrieve just only one with the is_guest key and value true

Geoff
  • 6,277
  • 23
  • 87
  • 197
  • If it's always the first, just access it via `route.data[0].is_guest` – Zenoo Jan 15 '18 at 14:03
  • 1
    Do you not want `.filter` if you're trying to return a subset of the data? – Dan Gamble Jan 15 '18 at 14:04
  • @Zenoo some routes dont have the is_guest property so i cannot simply use the use an index. – Geoff Jan 15 '18 at 14:05
  • @DanGamble with .filter am getting an error route.data.filter is not a function, they are object not arrays. – Geoff Jan 15 '18 at 14:06
  • *"But the above fails returning all the objects"* No, it returns matching objects and `undefined` for all others -- because `map` builds a new array with an entry for every entry in the original, based on what you return from the callback. – T.J. Crowder Jan 15 '18 at 14:06
  • Possible duplicate of [Get JavaScript object from array of objects by value or property](https://stackoverflow.com/questions/13964155/get-javascript-object-from-array-of-objects-by-value-or-property) – Zenoo Jan 15 '18 at 14:07

3 Answers3

1

Sounds like you want Object.values, not Object.keys, and filter:

const data = Object.values(route.data).filter(e => e.is_guest);

Object.values is fairly new, but present on up-to-date Node, and entirely polyfillable.

Example:

const route = {
  data: [
    {is_guest: true},
    {permission:'is_allowed_ip'}
  ]
};
const data = Object.values(route.data).filter(e => e.is_guest);

console.log(data);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Using E6:

data.filter(o => o.is_guest)
Luis Nolazco
  • 1,272
  • 1
  • 9
  • 7
0

You can use the filter method.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

I added some ids into your array just to make easier to understand.

// added ids to exemplify 
const data = [ 
  {id: 1, is_guest: true}, 
  {id: 2, permission:'is_allowed_ip'},
  {id: 3, is_guest: true}, 
  {id: 4, is_guest: false}, 
 ]

// filter results
const filtered = data.filter(item => item.is_guest)

// just to show the result
document.querySelector('.debug').innerHTML = JSON.stringify(filtered, null, 2);
<pre><code class="debug"></code></pre>
Eduardo Stuart
  • 2,869
  • 18
  • 22