无法使用地图将对象添加到另一个对象

时间:2015-09-10 05:46:51

标签: javascript underscore.js

我遇到了一个我以前从未见过的问题。这是我正在做的事情的本质

var doStuff = function(stuff, otherstuff){
   return _.map(stuff, function(s){

     // Thing needed is a fairly big object 
     var thingNeeded = _.find(otherstuff, function(os){
       return os.whatineed;
     });

     var new_thing = _.clone(s);
     new_thing.new_field = thingNeeded;
     return new_thing;
   });
};

但是这会返回一个原始stuff列表的列表!如果我做这种变化,甚至会发生这种情况

var doStuff = function(stuff, otherstuff){
   return _.map(stuff, function(s){

     // Thing needed is a fairly big object 
     var thingNeeded = _.find(otherstuff, function(os){
       return os.whatineed;
     });


     s.new_field = thingNeeded;
     return s;
   });
};

var doStuff = function(stuff, otherstuff){
   return _.map(stuff, function(s){

     // Thing needed is a fairly big object 
     var thingNeeded = _.find(otherstuff, function(os){
       return os.whatineed;
     });


     s['new_field'] = thingNeeded;
     return s;
   });
};

使用_.extend()_.create()的变体形式。它也不适用于数组原型中的地图。

我不知道我在这里做错了什么。它完全无视我添加领域。有人可以帮忙吗?

编辑:用于记录

[{thing: 1}, {thing: 2}].map(function(t){
  t.welp = 'welp';
});

将按预期返回[{thing: 1, welp: 'welp'}, {thing: 2, welp: 'welp'}]。所以它在地图内的某个地方。

再次编辑:

var doStuff = function(stuff, otherstuff){
   return _.map(stuff, function(s){

     // Thing needed is a fairly big object 
     var thingNeeded = _.find(otherstuff, function(os){
       return os.whatineed;
     });

     var new_thing = _.clone(s);
     new_thing.new_field = thingNeeded;
     console.log('stuff:', new_thing.new_field);
     return new_thing;
   });
};

console.log将返回我们期望的值(thingNeeded)。

谢谢!

0 个答案:

没有答案