0
\$\begingroup\$

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

Model:

var directory_model = {
 "link_title": {
 "value": 1, // This needs to be filled with object data
 "validation": null
 },
 "link_desc": {
 "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.

asked Apr 1, 2016 at 13:32
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

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];
 }
}
answered Apr 20, 2016 at 8:40
\$\endgroup\$
0
\$\begingroup\$

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;
 }
});
answered Apr 20, 2016 at 6:38
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.