简体   繁体   English

lodash在数组的每个对象中分配一个字段

[英]lodash assign a field in each object in array

I have an array that contains a lot of objects that looks like this: 我有一个包含很多对象的数组,看起来像这样:

obj = {name: 'Hello', isUpdated:false};

Now, I wish to use lodash to assign all isUpdated variables from false to true . 现在,我希望使用lodash将所有isUpdated变量从false分配给true

I have been looking at their documentation and found: 我一直在看他们的文档,发现:

_.assignIn(object, [sources])

However, I'm not quite sure it's what I needed. 但是,我不太确定这是我所需要的。 Maybe I need to combine two different methods? 也许我需要结合两种不同的方法?

I was hoping that some of you guys may know, thanks. 我希望你们中的某些人可能知道,谢谢。

If you don't want to mutate the source array, then you can use _.assign() together with _.map() . 如果您不想改变源数组,则可以将_.assign()_.map()一起使用。

var result = _.map(array, v => _.assign({}, v, { isUpdated: true }));

 var array = [{ name: 'hoo', isUpdated: false }, { name: 'yeah', isUpdated: false }, { name: 'Hello', isUpdated: false }, { name: 'Hello', isUpdated: false }, { name: 'Hello', isUpdated: false }, { name: 'yeahv', isUpdated: false }]; var result = _.map(array, v => _.assign({}, v, { isUpdated: true })); document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>'); 
 <script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script> 


A vanilla JS alternative would be to use Array.prototype.map() with Object.assign() 普通的JS替代方法是将Array.prototype.map()Object.assign()一起使用

var result = array.map(v => Object.assign({}, v, { isUpdated: true }));

 var array = [{ name: 'hoo', isUpdated: false }, { name: 'yeah', isUpdated: false }, { name: 'Hello', isUpdated: false }, { name: 'Hello', isUpdated: false }, { name: 'Hello', isUpdated: false }, { name: 'yeahv', isUpdated: false }]; var result = array.map(v => Object.assign({}, v, { isUpdated: true })); document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>'); 

as @Tushar said in his comment, you don't actually need Lodash if you're in a reasonably modern browser, the array object has it's own map function that'll do the trick (and Lodash iirc uses it under the hood if present). 正如@Tushar在他的评论中所说,如果您使用的是相当现代的浏览器,则实际上并不需要Lodash,该数组对象具有它自己的map函数即可解决问题(Lodash iirc如果存在则在幕后使用它)。

In any case, to answer you for Lodash, I'd use _.map() as well: 无论如何,要回答Lodash的问题,我也将使用_.map()

_.map(arr, (o) => { o.isUpdated = true; return o});

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

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