Node.js - 按值在数组中查找对象

时间:2017-11-28 12:27:15

标签: javascript node.js mongoose mongoose-schema

我试图通过其中一个键的值来获取数组中的对象。

数组:

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

3 个答案:

答案 0 :(得分:2)

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"))

答案 1 :(得分:0)

目前还不清楚你在问什么,但是搜索对象属性值将是这样的Ramda:

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

R.find(R.propEq("resource", "login"), a.privileges);

答案 2 :(得分:0)

您可以使用find方法:

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

var objFound = a.privileges.find(obj => obj.resource === "user");