强调每个错误的价值观?

时间:2014-05-28 01:28:10

标签: javascript json underscore.js

有人可以帮助我理解为什么我没有得到预期的输出。我有以下代码。

var targetArray = [];
var tempVar = {};
var json = [
    { id:1, available:false, value:'vodka', quantity:1 },
    { id:2, available:true, value:'WINE', quantity:13 },
    { id:2, available:true, value:'WINE', quantity:13 },
    { id:3, available:true, value:'gin', quantity:42 },
    { id:4, available:true, value:'scotch', quantity:21 },
    { id:5, available:true, value:'WHISKEY', quantity:123 },
    { id:100, available:true, value:'schnapps', quantity:5 },
    { id:120, available:false, value:'beer', quantity:0 },
    { id:2, available:true, value:'WINE', quantity:13 },
    { id:999, available:true, value:'rum', quantity:55 },
    { id:1, available:false, value:'Vodka', quantity:1 },
    { id:13, available:true, value:'brandy', quantity:3 },
    { id:42, available:true, value:'Tequila', quantity:88 }
];

_.each(json, function(value){
    tempVar.value = value.value;
    tempVar.available = value.available;
    targetArray.push(tempVar);
  });

alert(JSON.stringify(targetArray));

我的输出如下。

[{"value":"Tequila","available":true},{"value":"Tequila","available":true},{"value":"Tequila","available":true},{"value":"Tequila","available":true},{"value":"Tequila","available":true},{"value":"Tequila","available":true},{"value":"Tequila","available":true},{"value":"Tequila","available":true},{"value":"Tequila","available":true},{"value":"Tequila","available":true},{"value":"Tequila","available":true},{"value":"Tequila","available":true},{"value":"Tequila","available":true}]

当我尝试这个时,它会提醒我每个值,就像它应该的那样。

_.each(json, function(value){
    alert(JSON.stringify(value.value));
});

我错过了什么吗?

这里是小提琴

http://jsfiddle.net/a6Rx4/421/

提前致谢。

1 个答案:

答案 0 :(得分:3)

你正在推动同一个对象。 相反,每次都创建一个新对象,如下所示:

_.each(json, function(value){
    targetArray.push({value: value.value, available: value.available });
});

对于这种情况,您还可以使用.map方法:

var json = [
    { id:1, available:false, value:'vodka', quantity:1 },
    { id:2, available:true, value:'WINE', quantity:13 },
    { id:2, available:true, value:'WINE', quantity:13 },
    { id:3, available:true, value:'gin', quantity:42 },
    { id:4, available:true, value:'scotch', quantity:21 },
    { id:5, available:true, value:'WHISKEY', quantity:123 },
    { id:100, available:true, value:'schnapps', quantity:5 },
    { id:120, available:false, value:'beer', quantity:0 },
    { id:2, available:true, value:'WINE', quantity:13 },
    { id:999, available:true, value:'rum', quantity:55 },
    { id:1, available:false, value:'Vodka', quantity:1 },
    { id:13, available:true, value:'brandy', quantity:3 },
    { id:42, available:true, value:'Tequila', quantity:88 }
];

var targetArray = json.map(function (e) {
  return { value: e.value, available: e.available };
});