node.js - Google Cloud Datastore 从数组中获取对象
问题描述
如何使用 NodeJs Datastore SDK 通过 id 从数组属性中检索对象?
我有一个名为 Team 的 Kind,其属性为 Players。我需要通过 id 获得一个玩家。
这是团队实体的示例:
{
"id" : "T01",
"name" : "My Team",
"city" : "London",
"players" : [
{
"id" : "P01",
"name" : "John",
"lastName" : "Doo",
"height" : "181"
},
{
"id" : "P02",
"name" : "Mario",
"lastName" : "Rossi",
"height" : "185"
}
]
}
解决方案
一种可能的解决方案是查询所有 Teams,然后使用for 循环搜索每个 Team 的player属性。下面的示例将其值声明并设置为与所需 ID 匹配的 Player 对象数组:queryResult
const query = datastore.createQuery('Team');
const desiredId = "P01";
const queryResult = await datastore.runQuery(query).then(results => {
const teams = results[0];
let players = [];
teams.forEach(team => {
// Below we search for a valid player with the desired ID
const matchedPlayer = team.players.find(player => player.id == desiredId);
// If we find a valid player we "push it" to the players array.
if(matchedPlayer) {
players.push(matchedPlayer);
}
});
return players;
});
推荐阅读
- windows-10 - Unable to Update the SCCM Consol
- angular - import * as someName from '@angular/core' in angular 2/4/5/6/latter 版本
- ios - 在两个纬度和经度之间绘制折线
- sbt - 从 ScalaJs 调用旋转模板
- javascript - 为什么html音频自动播放不起作用
- excel - 复制值并排除 #N/A 单元格
- excel - 如何在 Excel 中计算“客户月数”
- bash - 更改终端窗口背景颜色和文本
- .htaccess - .htaccess 重定向无法正常工作?
- python - 粗糙集:Python 中的快速归约/特征选择