简体   繁体   English

向数组的每个项目添加一个额外的属性

[英]Add a extra property to each item of an array

I have an array of items called documents . 我有一系列称为documents的物品。 Each item has the same bunch of properties. 每个项目都具有相同的属性。 I wanted to add an additional property to each item called serviceShortCode . 我想为每个名为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. 一旦这段代码执行完毕,我将得到只有serviceShortCode的对象数组,所有其他属性都消失了。

Why so? 为什么这样?

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. 确保原始对象保持不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM