如何从普通对象创建特定对象以在mongodb的$set参数中使用

huangapple go评论106阅读模式
英文:

How to make a specific object from an ordinary object for use in a mongodb $set parameter

问题

将JavaScript对象转换为MongoDB的$set参数的方法:

  1. let object = {
  2. a: {
  3. b: 12,
  4. c: {
  5. d: 13
  6. }
  7. }
  8. };
  9. // 转换为MongoDB的$set参数
  10. let transformedObject = {
  11. "a.b": object.a.b,
  12. "a.c.d": object.a.c.d
  13. };

现在你可以将transformedObject用作MongoDB updateOne 方法中的 $set 参数。

英文:

How can I transform this object in JavaScript:

  1. let object = {
  2. a: {
  3. b: 12
  4. c: {
  5. d: 13
  6. }
  7. }
  8. }

Into this:

  1. let object = {"a.b": 12, "a.c.d": 13}

I want to modify object and use it like a $set param in mongodb in updateOne method

答案1

得分: 0

Use Object.entriesObject.entries to iterate over each [key, value] pair using flatMap 使用 flatMap 迭代每个[key, value]对, and recursively get to the leaves of the object tree, building up the path to each leaf in the p array. 并递归地访问对象树的叶子节点,在p数组中建立到每个叶子节点的路径。 Once a leaf is found, use join to turn the path array into a dotted path string. 一旦找到一个叶子节点,使用join将路径数组转换为点分路径字符串。 flatMap is used to ensure that a flat array of [key, value] pairs are returned, instead of a nested array. 使用flatMap确保返回的是一个扁平的[key, value]对数组,而不是嵌套的数组。 Finally, we use Object.fromEntries to turn the list of pairs into an array. 最后,我们使用Object.fromEntries将键值对列表转换为数组。

英文:

Use Object.entries to iterate over each [key, value] pair using flatMap, and recursively get to the leaves of the object tree, building up the path to each leaf in the p array. Once a leaf is found, use join to turn the path array into a dotted path string. flatMap is used to ensure that a flat array of [key, value] pairs are returned, instead of a nested array. Finally, we use Object.fromEntries to turn the list of pairs into an array.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

  1. let data = {
  2. a: {
  3. b: 12,
  4. c: {
  5. d: 13
  6. }
  7. },
  8. e: {
  9. f: {
  10. g: 6
  11. }
  12. }
  13. }
  14. const f = (v, p=[]) =&gt; typeof v === &#39;object&#39; ?
  15. Object.entries(v).flatMap(([k, v]) =&gt; f(v, [...p, k])) : [[p.join(&#39;.&#39;), v]]
  16. console.log(Object.fromEntries(f(data)))

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月1日 05:14:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76377351.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定