Sachin Kainth
Sachin Kainth

Reputation: 46760

Add a extra property to each item of an array

I have an array of items called documents. Each item has the same bunch of properties. I wanted to add an additional property to each item called serviceShortCode. I wrote the following code to achieve this

documents = _.map(documents, function (doc) {
                return _.extend({                    
                    serviceShortCode: View.getServiceName(doc.publishedIn)      
                });
            });

Once this code finishes executing I get an array of objects with only the serviceShortCode, all other properties have vanished.

Why so?

Upvotes: 0

Views: 71

Answers (1)

major-mann
major-mann

Reputation: 2652

You seem to be missing the document from the extend call.

Change

return _.extend({                    
    serviceShortCode: View.getServiceName(doc.publishedIn)
});

To

return _.extend(doc, {                    
    serviceShortCode: View.getServiceName(doc.publishedIn)
});

Or, alternatively

return _.extend({}, doc, {                    
    serviceShortCode: View.getServiceName(doc.publishedIn)
});

to ensure the original objects remain unmodified.

Upvotes: 1

Related Questions