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.

\$\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];
    }
}
\$\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;
    }
});
\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.