javascript - forEach is not a function after object merge -
i created method based on this question, modified recursive. seems work, issue having getting error says:
uncaught typeerror: this.config.routes.foreach not function
var obj = { config: { maxloadloop: 5, author: {color: "red"} }, run: function(settings){ this.config = this.mergeoptions(this.config, settings); this.config.routes.foreach(function(){/* stuff */}); }, mergeoptions: function(obj1, obj2){ var obj3 = {}; for(var attrname in obj1){ obj3[attrname] = obj1[attrname]; } for(var attrname in obj2){ if(array.isarray(obj2[attrname]) || typeof obj2[attrname] === "object"){ obj3[attrname] = this.mergeoptions(obj3[attrname], obj2[attrname]); }else{ obj3[attrname] = obj2[attrname]; } } return obj3; } }; obj.run(mycustomsettings); i merging following 2 objects:
{ maxloadloop: 5, author: {color: "red"} } and (json converted object):
{ "author": { "name": "me", "email": "my email" }, "routes": [ { "route": "/home", "template": "/templates/home.html", "default": true }, { "route": "/games", "template": "/templates/games.html" } ] } the 2 seem merge fine, except error mentioned above...
i changed line 2:
var obj3 = (!obj1 && array.isarray(obj2)) ? [] : {}; if in case obj1 not exist , obj2 array, output should array.
if want handle case both obj1 , obj2 arrays, need put in bit more work.
Comments
Post a Comment