I can not understand how to overwrite the value of an object on js with the help of for in ?

var Test = (function () { "use strict"; var def = { test: '1', test2: '2' }; function _run(data) { for (def in data) { /* ???? */ } //результат console.log(def.test) // >> hi } return { run: function (data) { _run(data); } } }()); Test.run({ test: 'hi', test2: 'hi2' }); 

Test.run(); - values ​​remain default (def.test = 1, def.test2 = 2)

Test.run({test: 'hi'}); - overwrite only test, leave test2 as default. Test.tun({olala: 'hi'}); - give the error "no such parameter".

  • and what should be the output? - Grundy
  • Updated his question - Evgeniy Mikhalhenko
  • still not clear. Need to change the values ​​in the def object? and if in the transferred object there are fields which are not in object def? - Grundy
  • Yes, that's right, if you don’t have them, then you ’ll get a mistake - Evgeniy Mikhalichenko
  • in which case to display an error? if the object is passed {test:'hi'} and {test:'hi', test2:'hi', test3:'hi'} , {test:'hi', test3:'hi'} ? - Grundy

1 answer 1

It is necessary to check that prop (the data property) is a property in def , and if so, then replace the value of this property in def , otherwise “throw away” the error.

 for (var prop in data) { if (def.hasOwnProperty(prop)) { def[prop] = data[prop]; } else { throw new Error(prop + ' isn\'t existing property'); } } 

In your example, you are overwriting the def object (inside for-in ).

  • one
    if in def one of the fields is undefined or 0 or false, etc. the code will throw an error instead of an assignment - Grundy
  • if in def any of the fields is undefined, the code will throw an error instead of an assignment. undefined may be a valid field value - Grundy
  • @Grundy updated the answer - saaaaaaaaasha
  • Thanks, helped) - Evgeniy Mikhalhenko