【问题标题】:Can't add object to another object with map无法使用地图将对象添加到另一个对象
【发布时间】:2015-09-10 05:46:50
【问题描述】:

我遇到了一个在 javascript 中从未见过的问题。这是我正在做的事情的精髓

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)。

谢谢!

【问题讨论】:

  • 尝试克隆需要的东西?
  • 在最后两种情况下,您将 'os' 传递给 'find' 回调,然后在其中使用'otherstuff'。在第一种情况下,如果 'otherstuff' 上不存在 '.whatineed',那么你将得到你所看到的。
  • @caasjj 感谢您指出错字。
  • @korven 克隆无法解决任何问题。

标签: javascript underscore.js


【解决方案1】:

我认为你在地图迭代器中使用了一些东西,而你应该使用当前迭代的对象's'。

这是一个工作小提琴http://jsfiddle.net/rzkvne23/

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

     var thingNeeded = _.find(otherstuff, function(os){
       return os.whatineed === 2;
     });

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

var a = [{},{},{}];
var b = [{whatineed: 1},{whatineed:2},{whatineed:3}];

console.dir(doStuff(a,b));

【讨论】:

  • 这将永远无法解决。你又发现了一个错字。对不起。在实际代码中,我正在克隆 s,类似于我使用 s 的其他示例。我正要放弃这个,去做别的事情。正是因为这个原因,我讨厌 javascript。
猜你喜欢
  • 2021-07-14
  • 2017-01-19
  • 2021-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-26
相关资源
最近更新 更多