user385729
user385729

Reputation: 1984

map in javascropt/node or another clean approach

I have two arrays (models and modelsErrors), I want to map the reuslt and merge them in a way that if the inputs are the following :

models=['user', 'employee', 'customers'];
modelsErrors=['userError', 'employeeError', 'customersError'];

Desired output should be:

Results=[{model: user, err: userError}, {model: employee, err: employeeError}, {model: customers, err: customersError}]

I guess it is possible to use .map of javascript; if not I'm looking for a clean way like .map() function: My attempt:

    models=['user', 'employee', 'customers'];
    modelsErrors=['userError', 'employeeError', 'customersError'];
    var results = models.map(function(model){
        return {model: model, err: modelsErrors[model]}
    })

    console.log(results);

I'm looking for a clean way if map is not possible... Please let me know if you need more clarification Thanks

Upvotes: 1

Views: 59

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173562

You were almost there; just use the index argument of the callback to find the corresponding value of the other array:

models.map(function(value, index) {
    return {
        model: value,
        err: modelsErrors[index]
    };
});

Upvotes: 3

Related Questions