【问题标题】:Getting the index of matched value获取匹配值的索引
【发布时间】:2020-03-22 04:57:34
【问题描述】:

我在 mongodb atlas 中创建了在线集群,然后创建了 mongodb 缝合应用程序,在缝合 javascript 编辑器中,我如何在匹配时获取 x 的索引?示例:

{
"_id": 5646546,
"items":[   {"x": 12, "y": 4} ,  {"x": 12, "y": 4}   ]

}

所以当 x= 12 时,索引应该是 0

【问题讨论】:

  • 所以你想写一个javascript函数?
  • 是的,我用的是python,所以对javascript有点了解
  • 为了解释更多,我使用stitch将集合导入到goole表中,一切正常我想知道的是使google表中的更改同步到我的数据库所以我要制作google app脚本返回 id 并更改 > 在缝合侧我将搜索 id ,即我的示例中的 (x) 并更新 y

标签: mongodb mongodb-stitch


【解决方案1】:

你可以像下面这样在stitch中编写一个javascript函数:

const getIndex = (inputArray, match) => {
  return inputArray.findIndex(element => element.x == match);
};

let obj = {
  _id: 5646546,
  items: [
    { x: 12, y: 4 },
    { x: 12, y: 4 }
  ]
};

let obj2 = {
  _id: 5646547,
  items: [
    { x: 121, y: 4 },
    { x: 12, y: 4 },
    { x: 122, y: 4 }
  ]
};

console.log(getIndex(obj.items, 12)); // prints 0
console.log(getIndex(obj2.items, 122)); // prints 2

【讨论】:

  • 感谢您的解决方案,但我遇到了错误 imgur.com/a/aP5QKJ8
  • @ManafA.B :我认为问题在第 17 行,删除它,您还需要记录响应吗?您也可以删除 cmets prints..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-26
  • 2019-08-11
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
相关资源
最近更新 更多