简体   繁体   中英

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 .

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() .

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()

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).

In any case, to answer you for Lodash, I'd use _.map() as well:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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