英文:
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.entries
用 Object.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=[]) => typeof v === 'object' ?
Object.entries(v).flatMap(([k, v]) => f(v, [...p, k])) : [[p.join('.'), v]]
console.log(Object.fromEntries(f(data)))
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论