如何在GraphQL中更新多层嵌套数组内的指定字段值
不同场景下的访问/更新语句
1. 原生JavaScript写法
// 定位目标option const targetOption = data.item.options.find(opt => opt.label === 'Top'); // 定位目标spec const targetSpec = targetOption.specs.find(spec => spec.label === 'Right'); // 直接更新value属性 targetSpec.value = '你要设置的新值'; // 可选链式写法(避免字段不存在时报错) const targetValue = data.item.options?.find(opt => opt.label === 'Top')?.specs?.find(spec => spec.label === 'Right')?.value;
2. Python写法
# 定位目标option target_option = next(opt for opt in data['item']['options'] if opt['label'] == 'Top') # 定位目标spec target_spec = next(spec for spec in target_option['specs'] if spec['label'] == 'Right') # 更新value属性 target_spec['value'] = '你要设置的新值'
3. MongoDB更新语句
如果该结构存储在MongoDB文档中,更新语句如下:
db.collection.updateOne( { "item.options.label": "Top" }, { $set: { "item.options.$[opt].specs.$[spec].value": "新值" } }, { arrayFilters: [ { "opt.label": "Top" }, { "spec.label": "Right" } ] } )
4. JSONPath定位写法
用JSONPath直接定位目标节点的语法:
$..options[?(@.label=='Top')].specs[?(@.label=='Right')].value
内容的提问来源于stack exchange,提问作者jakey_dev
相关产品推荐
相关产品推荐

