underscore.js TypeError:Object ...没有方法'push'

时间:2014-11-22 06:40:02

标签: javascript underscore.js

我想在每个办公室数组中添加一个新值:

{
  "name" : "HQ",
  "office" : [ 
    {
      "name" : "Office1",
      "_id" : ObjectId("54671a5e82092cbc3f1e6104")
    }, 
    {
      "name" : "Office2",
      "_id" : ObjectId("54671a5e82092cbc3f1e6103")
    }
  ]
}

我正在尝试使用underscorejs:

var offices = [];
_.each(doc.offices, function(value){
  offices.push(value.push({"distance": distanced}));
}

但我得到TypeError: Object ... has no method 'push'

使用underscorejs有没有更快的方法呢?

1 个答案:

答案 0 :(得分:1)

传递给_.each函数的值是诸如{name: ...}之类的对象,因此您试图将对象推送到对象上。你想做以下的事吗?

var offices = [];
_.each(doc.office, function(value) {
  value.distance = distanced;
  offices.push(value);
});