# Nested values copies from one object to another

Here is a nodejs code that copies values from one object (submitted from a firm) to a model object.

Model:

var directory_model = {

"value": 1, // This needs to be filled with object data
"validation": null
},

"value": 2, // This needs to be filled with object data
"validation": null
},
};


Object values that must get into the model:

   { link_title: 'test1', link_desc: 'test2' }


Here is the code that does, it with lodash. This code does the job:

_.forOwn(directory_model, function(directory_model_value, directory_model_key) {
_.forOwn(fields, function(fields_value, fields_key) {
"use strict";
if (directory_model_key === fields_key)  {
directory_model[directory_model_key].value = fields_value;
}
});

});


I don't like the nested loop, and would like to know if you know another way to do this. I found several ways, but none of them works, because of the nested properties.

Why bother with libraries? This doesn't need anything more than pure JS. Assuming the incoming data is stored in fields:

var keys = Object.keys(fields);
for(var i = 0; i < keys.length; i++) {
var key = keys[i];
if(directory_model[key]) {
directory_model[key].value = fields[key];
}
}


I am not 100% sure what you are trying to achieve.

If you are not sure that your fields (form i guess) contains only keys that exist in directory_model, I recommend assigning the values in one iteration, with a simple check:

_.forOwn(fields, function (fields_value, fields_key) {
if (directory_model[fields_key]) {
directory_model[fields_key].value = fields_value;
}
});