向Javascript对象动态添加新对

Adding new pair to Javascript object dynamically

本文关键字:添加 动态 Javascript 对象      更新时间:2023-09-26

Node.js应用程序中,我有一个名为user的对象,其内容如下:

{
   name:'john',
   family:'jackson'
}

我想像这样动态地添加一对新的:

user["city"] =  "new york";

但它不起作用!当我这样打印时:

console.log(user);

我看到了与上面相同的内容:

{
   name:'john',
   family:'jackson'
}

但当我打印这个时:

console.log(user.city);

它打印这个:

new york

但为什么??我把这个结果发送到浏览器,它仍然没有city键/值!

更新:

在一个简单的javascript中,我解释的所有东西都能工作。我的问题是,当我使用node.js时,在使用Mongoose从数据库中获取一些数据后,如下所示:

Users.find({followings:{$elemMatch:{$in:[userID]}}}).exec(function(err, users){
     users[0]["city"] =  "new york"; // this doesn't work. this adds city to users but doesnt show in console.log(users[0])
});

但为什么呢?users是一个常规的Javascript对象。我为什么会有这种行为?

我发现了问题所在。当我执行mongoose查询时,结果不是一个普通的javascript对象。通过使用lean(),我可以告诉Mongoose跳过创建常规Mongoose模型。然后我改了这个:

Users.find({followings:{$elemMatch:{$in:[userID]}}}).exec(function(err, users){
     users[0]["city"] =  "new york"; // this doesn't work. this adds city to users but doesnt show in console.log(users[0])
});

到此:

Users.find({followings:{$elemMatch:{$in:[userID]}}}).lean().exec(function(err, users){
     users[0]["city"] =  "new york"; //works now!
});

它起作用了!

试试这个:

var user = {'name':'John'};
user["city"] = "New York";
console.log(user);

你能试试这个简单的代码并查看哪些节点日志吗?它应该吐出这个:

Object {name: "John", city: "New York"}

解释:

在我们的示例中,我们设置了一个属性为name、值为John的Object第二行只是添加一个额外的属性city和一个值New York第三行记录具有新属性的对象