2

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.

3
  • Can you add complete array and the expected array. Commented Jul 13, 2016 at 11:07
  • 3
    arr = arr.map(function(o) { o.isUpdated = true; return o; }); Commented Jul 13, 2016 at 11:09
  • The above will modify the original array even without reassigning. A more explicit way to do this would be arr.forEach(o => o.isUpdated = true); Commented Jul 13, 2016 at 11:34

2 Answers 2

4

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>');

Sign up to request clarification or add additional context in comments.

Comments

0

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});

2 Comments

Lodash doesn't use the native Array.prototype.map() as it is slow. Here's the reference.
OK, thanks, I couldn't recall for sure. I knew they used native stuff in some cases, and not others.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.