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

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

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

问题

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

let object = {
    a: {
        b: 12,
        c: {
            d: 13
        }
    }
};

// 转换为MongoDB的$set参数
let transformedObject = {
    "a.b": object.a.b,
    "a.c.d": object.a.c.d
};

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

英文:

How can I transform this object in JavaScript:

let object = {
    a: {
        b: 12
        c: {
           d: 13
        }
    }
}

Into this:

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 -->

let data = {
  a: {
    b: 12,
    c: {
      d: 13
    }
  },
  e: {
    f: {
      g: 6
    }
  }
}

const f = (v, p=[]) =&gt; typeof v === &#39;object&#39; ? 
  Object.entries(v).flatMap(([k, v]) =&gt; f(v, [...p, k])) : [[p.join(&#39;.&#39;), v]]

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:

确定