如何在 Loopback 中访问数组的嵌套属性?

How do I access the nested properties of an array in Loopback?

这里,
res = 检索到的结果数组

res = [ Object, Object, Object... Object ]

每个对象看起来像这样:

Object{
    "userId": "ab1ce",
    "groupId": "a1de2"
}

现在,结果有一个这样的对象数组,我如何访问这些对象中存在的 userId?

像这样:

res.forEach(function(obj){
 console.log(obj.userId);
});

对于数组的每一项,0 到 n,您可以从数组中获取对象,然后访问它的属性。

例如 res[0].userId 将为您获取第一项的用户 ID。

你可能应该阅读一些 Javascript 入门手册以获得基础知识,info page or this one 中列出了一些很好的

res 是一组对象,因此要访问一个对象,您必须使用如下内容:

res[index];

其中 index 是一个下标,它告诉您想要数组的哪一项。由于数组是从 0 开始索引的,因此 index 应该在 [0, res.length - 1].

范围内

然后当您访问数组 res 中的项目时,您将获得一个可以使用以下任一方式访问的对象:

res[index].key;
// OR
res[index]["key"];

其中 key 是该对象的 属性 的名称。因此,要获取数组中第一个对象的 userId,请使用:

var mySecondObject = res[1]; // 0 is the first, 1 is the second ...
var theId = mySecondObject.userId; // or theId = mySecondObject["userId"];

或像这样的一行:

var theId = res[1].userId;

注意: res是一个数组,你可以用很多不同的方式循环它(for循环,forEach ...) here 是一个如何做到这一点的例子。

如果您在环回中使用它,您可以在 where 子句中使用 inq 属性 以便从数组内部搜索一些东西 例如:

modelname.method({ where: { "property": { inq [ res.property  ] } } }, (err, res) => {
    if(err) { return console.error(err);
    } else {
        return true;
    }
});

inq 运算符检查指定 属性 的 value 是否匹配 [=] 中提供的任何值31=]数组。一般语法是:

{where: { property: { inq: [val1, val2, ...]}}}

其中:

属性是被查询模型中的属性(字段)的名称。

val1、val2 等, 数组中的文字值

inq 运算符的示例

Posts.find({where: {id: {inq: [123, 234]}}}, 
    function (err, p){... });

答案特定于环回。