获取带条件的特定对象字段并对其进行操作
Get specific object field with condition and make opertion on it
我有这样的对象:
{
buildings: {
"1": {
"l": 0 ,
"r": 0 ,
"s": 0 ,
"type": "GoldMine" ,
"x": 2 ,
"y": 15
} ,
"10": {
"l": 0 ,
"r": 6 ,
"s": 2 ,
"type": "MagicMine" ,
"x": 26 ,
"y": 22
}
} ,
[...]
}
我想获取建筑物类型为 "GoldMine" 的对象。
我尝试了 map
:
r.table("Characters").map(function(row) {
return row("planet")("buildings")
})
使用 keys()
我可以迭代它:
r.db("Unnyworld").table("Characters").map(function(row) {
return row("planet")("buildings").keys().map(function(key) {
return "need to get only buildings with type == GoldMine";
})
}).limit(2)
但它 returns 所有建筑物。我只想获得类型 == GoldMine 和更改字段 x
.
的建筑物
类似这样的方法可能有效:
r.table('Characters')
.concatMap(function(doc) {
return doc("planet")("buildings").keys().map(function(k) {
return {id: doc('id'), key: k, type: doc("planet")("buildings")(k)('type'), x: doc("planet")("buildings")(k)('x')}
})
})
.filter(function(building) {
return building('type').eq('GoldMine')
})
.forEach(function(doc) {
return r.table('Characters').get(doc('id'))
.update({
planet: {buildings: r.object(doc('key'), {x: 1111111})}
})
})
基本上通过使用 concatMap
然后 filter
从 building
创建平面数组。使用结果数据,我们可以对其进行迭代并更新为我们想要的值。
我有这样的对象:
{
buildings: {
"1": {
"l": 0 ,
"r": 0 ,
"s": 0 ,
"type": "GoldMine" ,
"x": 2 ,
"y": 15
} ,
"10": {
"l": 0 ,
"r": 6 ,
"s": 2 ,
"type": "MagicMine" ,
"x": 26 ,
"y": 22
}
} ,
[...]
}
我想获取建筑物类型为 "GoldMine" 的对象。
我尝试了 map
:
r.table("Characters").map(function(row) {
return row("planet")("buildings")
})
使用 keys()
我可以迭代它:
r.db("Unnyworld").table("Characters").map(function(row) {
return row("planet")("buildings").keys().map(function(key) {
return "need to get only buildings with type == GoldMine";
})
}).limit(2)
但它 returns 所有建筑物。我只想获得类型 == GoldMine 和更改字段 x
.
类似这样的方法可能有效:
r.table('Characters')
.concatMap(function(doc) {
return doc("planet")("buildings").keys().map(function(k) {
return {id: doc('id'), key: k, type: doc("planet")("buildings")(k)('type'), x: doc("planet")("buildings")(k)('x')}
})
})
.filter(function(building) {
return building('type').eq('GoldMine')
})
.forEach(function(doc) {
return r.table('Characters').get(doc('id'))
.update({
planet: {buildings: r.object(doc('key'), {x: 1111111})}
})
})
基本上通过使用 concatMap
然后 filter
从 building
创建平面数组。使用结果数据,我们可以对其进行迭代并更新为我们想要的值。