javascript - Array.push() and console.log() gives different variables -
i want modify this
var array = [{"host": ["example.com", "www.example.com"], "from": "test1", "to": "test2"}, {"host": ["example.net", "www.example.net"], "from": "test3", "to": "test4"}];
into on chrome 43.0.2357.134 m
[{"host": "example.com", "from": "test1", "to": "test2"}, {"host": "www.example.com", "from": "test1", "to": "test2"}, {"host": "example.net", "from": "test3", "to": "test4"}, {"host": "www.example.net", "from": "test3", "to": "test4"}];
i used code
array.foreach(function(rule){ rule.host.foreach(function(host){ var tmp = rule; tmp.host = host; result.push(tmp); }); });
but gives
[{"host": "www.example.com", "from": "test1", "to": "test2"}, {"host": "www.example.com", "from": "test1", "to": "test2"}, {"host": "www.example.net", "from": "test3", "to": "test4"}, {"host": "www.example.net", "from": "test3", "to": "test4"}];
when replace array.push
console.log()
log right variables. can not async issue array.push()
, because tried old array.length
way add array - no changes. may use foreach
wrong - there lot of array.prototype
methods - can't right one.
arrays , objects in javascript passed , assigned reference, not value. var tmp = rule
merely making second pointer original rule, overwriting data , printing each entry twice. achieve desired effect, must clone all of data in entries new entries.
array.foreach(function(rule){ rule.host.foreach(function(host){ result.push({ host: host, from: rule.from, to: rule.to }); }); });
Comments
Post a Comment