0

I am trying to get an object in an array by the value of one of its keys.

The array:

{
"privileges" : 
    [
      {
        "resource" : "login" ,
        "actions": ["true"]
      },
      {
        "resource":  "user" ,
        "actions": ["create","read"]
      }
    ]
}
Haythem Hedfi
  • 569
  • 1
  • 5
  • 11
  • What is the expected result please? – DSCH Nov 28 '17 at 12:38
  • I put console.log(user.role.privileges) and i got this privileges: [ { '0': [Object], '1': [Object], actions: [] } ] } – Haythem Hedfi Nov 28 '17 at 12:40
  • @HaythemHedfi Your accepted answer doesn't contain anything related to MongoDB, they why those tags? – Nidhin David Nov 28 '17 at 15:02
  • Possible duplicate of [Javascript: How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/javascript-how-to-filter-object-array-based-on-attributes) – Nidhin David Nov 28 '17 at 15:02

3 Answers3

3

let obj  = {
"privileges" : 
    [
      {
        "resource" : "login" ,
        "actions": ["true"]
      },
      {
        "resource":  "user" ,
        "actions": ["create","read"]
      }
    ]
}

function filterValue(value) {
return obj["privileges"].filter((object) => {
 return object["resource"] == value
})
}
console.log(filterValue("user"))
Rajkumar Somasundaram
  • 1,225
  • 2
  • 10
  • 20
1

You can use find method:

const a = {
    "privileges": [
      {
        "resource" : "login" ,
        "actions": ["true"]
      },
      {
        "resource":  "user" ,
        "actions": ["create","read"]
      }
    ]
};

var objFound = a.privileges.find(obj => obj.resource === "user");
David Vicente
  • 3,091
  • 1
  • 17
  • 27
0

It's unclear what you are asking, but searching for the object property value would be with Ramda like this:

const a = {
    "privileges": [
      {
        "resource" : "login" ,
        "actions": ["true"]
      },
      {
        "resource":  "user" ,
        "actions": ["create","read"]
      }
    ]
}

R.find(R.propEq("resource", "login"), a.privileges);
Risto Novik
  • 8,199
  • 9
  • 50
  • 66