所以我使用mongoDB进行迁移项目,将查询视为普通的javascript / JSON:
queryObj = {}; // our main object I pass to mongodb for queries
以下代码抛出错误
queryObj[inObj.row]['$eq'] = inObj.equals;
但这有效....
queryObj[inObj.row[i]] = {};
queryObj[inObj.row]['$eq'] = inObj.equals;
是否有一种简单的方法可以使具有许多嵌套属性的对象不必将它们定义为对象?我可以创建一个构造函数,但我假设它们是一个简单的内置解决方案,通过Object.create。
答案 0 :(得分:1)
我能想到的唯一方法是创建一个在需要时创建空对象的方法。
/**
* Sets a deep property on an object by creating any required
* objects in the hierarchy that may not yet exist
* @param {object} obj The object to receive properties
* @param {string} prop Dot separated deep property to set
* @param {*} value What to set the given property to
*/
function setProp(obj, prop, value) {
var parts = prop.split('.');
var i = 0;
for (; i < parts.length - 1; i++) {
if (typeof obj[parts[i]] === 'undefined') {
obj[parts[i]] = {};
}
obj = obj[parts[i]];
}
// Note that parts[i] is pointing to the last part of the deep property name
// and obj points to the nested object that contains the last deep property
obj[parts[i]] = value
}
var obj = {}
setProp(obj, 'a.b.c', 3);
console.log(obj.a.b.c); // 3
&#13;
对于你的情况你可以像
那样setProp( queryObj, inObj.row + ".$eq", inObj.equals );