我正在为 MongoDB 开发一个 mapReduce 脚本,但我遇到了一个相当初级的 JavaScript 问题:我无法构造嵌套对象的路径。设置是这样的:在reduce步骤中,我有一个嵌套对象,其中包含所有可能的属性(以及一些示例值)。
var result = {
computers: {
total: 12,
servers: {
total: 2,
os: {
unix: 2,
windows: 0
}
},
clients: {
total: 10,
os: {
unix: 3,
windows: 7
}
}
}
}
从映射步骤中,我得到如下传入文档:
var incoming = {
computers {
total: 1,
clients: {
total: 1,
os: {
windows: 1
}
}
}
}
传入文档在逻辑上是结果文档的子集:元素的顺序和可能的元素是相同的,只是不完整:一个可能只包含服务器数据,另一个可能只包含客户端数据,第三个可能只包含服务器数据。包含两者等。
我想遍历传入文档,并将每个属性的值添加到结果文档中的相应属性中。递归地遍历传入文档不是问题(我认为),但构建路径才是问题。我想出了以下代码:
var traverse = function(knots, path) {
for (var k in knots) {
if (knots[k] !== null && typeof(knots[k]) == "object") {
path = path[knots[k]];
traverse(knots[k], path);
}
else {
// do something to get rid of the root-level incoming object
var rest = incoming.computers;
result[rest][knots[k]] += incoming[rest][knots[k]];
}
}
};
traverse(incoming.computers, incoming.computers);
该脚本无法运行。我怀疑我尝试连接路径(第 4 行)并将其传递给加法运算符(第 7 行)的方法都已损坏。
MongoDB 响应“16722 TypeError:无法读取未定义的属性 '1'”,但我对此不太理解。
编辑:更改了上面的代码:现在使用对象调用 traverse[path] (遵循 Felix 的提示)。后续问题是我不知道在 else 子句中构造路径时如何摆脱“传入”根对象。 varrest=incoming.computers;
似乎并不能解决问题。至少 MongoDB 仍然响应与上面相同的错误。
最佳答案
我相信你想要的是
function clone(obj){
if(obj == null || typeof(obj) != 'object')
return obj;
var temp = obj.constructor(); // changed
for(var key in obj)
temp[key] = clone(obj[key]);
return temp;
}
function update( oldData, newData){
for (property in newData){
if (oldData[property] !== undefined){ // existing path - needs to be updated
if (typeof(oldData[property]) === 'number'){ // element is number (total) - just add it
oldData[property] += newData[property];
} else { // element is object - drill down
update( oldData[property], newData[property] );
}
} else { // new path - needs to be added
oldData[property] = clone(newData[property]);
}
}
}
它也将处理添加新对象..
(clone
方法复制自 Most efficient way to clone an object? )
假设想要的结果是
result = {
computers: {
total: 13,
servers: {
total: 2,
os: {
unix: 2,
windows: 0
}
},
clients: {
total: 11,
os: {
unix: 3,
windows: 8
}
}
}
}
关于javascript - 构造嵌套对象的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20596895/