【问题标题】:push object to an already existed javascript object将对象推送到已经存在的 javascript 对象
【发布时间】:2012-10-23 19:39:40
【问题描述】:

我使用 nodejs 和 mongodb。

我从以下 mongodb 查询中获取字典资源:

Profile.find(search,['_id', 'username'],function(err, res)

打印资源看起来像:

[
    {
        "username": "dan",
        "_id": "508179a3753246cd0100000e"
    },
    {
        "username": "mike",
        "_id": "508317353d1b33aa0e000010"
    }
]
}

我想向每个 res[x] 推送另一个键值对:

[
    {
        "username": "dan",
        "_id": "508179a3753246cd0100000e",
        "more info": {
            "weight": "80",
            "height": "175"
        }
    },
    {
        "username": "mike",
        "_id": "508317353d1b33aa0e000010"
    },
    "more info": {
        "weight": "80",
        "height": "175"
    }
]
}

我试过了:

var x=0 dic = [] while (x<res.length){ dic[x] = {} dic[x]=res[x] dic[x]["more info"] = {"wight" : weight, "height" : hight} x=x+1 } 但它被忽略了,我得到了

[
    {
        "username": "dan",
        "_id": "508179a3753246cd0100000e"
    },
    {
        "username": "mike",
        "_id": "508317353d1b33aa0e000010"
    }
]
}

感谢您的帮助。

【问题讨论】:

  • 体重和身高不会拼写? :) x 在哪里被定义?它在哪里增加?

标签: javascript object push add


【解决方案1】:

改用 for 循环。

for (var x = 0, len = res.length; x < len; ++x) { ... }

您需要先初始化变量x (var x = 0),然后在每次执行循环后递增它(++xx += 1)。

更新:

哦,好的。顺便说一句,您为什么要创建新数组(dic)? JavaScript 中的对象是通过引用传递的,所以如果你只修改单个结果(res[0]、res[1]),你会得到相同的结果。

dic[x] = {}; dic[x] = res[x] 没有意义,因为您创建了一个新对象 ({}),然后立即用res[x] 指向的对象覆盖它。

试试这个:

 res.forEach(function (item) {
   item['more info'] = { weight: weight, height: height };
 });

 console.log(res);

【讨论】:

  • 感谢您的回答。这不是问题,我只是忘了写在问题中
  • 再次感谢。仍然“更多信息”被忽略!甚至尝试过:item.save()
  • 等等,您是立即检查结果,还是再次从数据库中请求项目并期望它们被更新?如果您使用item.save(),则需要等待更改存储在数据库中,然后再次检索项目。使用回调函数来做到这一点。你的 mongodb 驱动程序肯定有一个自述文件。
  • 我正在立即检查结果。我找到的唯一解决方案是创建一个新字典并一次复制每个键和值,然后添加我想要的键和值。遍历结果并复制每个键和值以向结果中添加一个键值对似乎非常低效,但这似乎是唯一的方法
猜你喜欢
  • 2012-09-12
  • 2019-12-23
  • 2019-05-04
  • 1970-01-01
  • 2021-01-17
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
相关资源
最近更新 更多