0

I have JavaScript object:

myData = {
      items: [
        {
          flag: false,
          text: "good text"
        },
        {
          flag: true,
          text: "good text"
        },
        {
          flag: false,
          text: "good text"
        }
      ]
    }

How can I change text everywhere where flag = true.

For example only 2nd object need to be changed from "good text" to "bad text", because only this object in my example has flag = true.

I want to do this using Lodash in JavaScript.

4 Answers 4

1

If you have to use lodash, this should work:

_.forEach(myData.items, function (item) {
  if (item.flag) {
    item.text = 'bad text';
  }
});
Sign up to request clarification or add additional context in comments.

Comments

1

You can use this snippet to change the text.

myData.items = _.map(_.get(myData, 'items'), (item) => {
  if (item.flag) {
    item.text = "new text"
  }
  return item;
});

1 Comment

This will not work because item.flag datatype is number and you compare it to a string value.
0

You really don't need lodash for this..

Here is a solution without using it

myData.items.forEach(item => item.text = item.flag ? "bad text" : item.text)

const myData = {
      items: [
        {
          flag: false,
          text: "good text"
        },
        {
          flag: true,
          text: "good text"
        },
        {
          flag: false,
          text: "good text"
        }
      ]
    };

console.log(JSON.stringify(myData.items));

myData.items.forEach(item => item.text = item.flag ? "bad text" : item.text);

console.log(JSON.stringify(myData.items));

Comments

0

How about: _(myData.items).filter('flag').each(x => x.text='bad text');

4 Comments

It works, but it will loop the list twice (first full list, then filtered list)
Hmm...are you sure, doesn't lodash use lazy evaluation when chaining functions (per the docs): lodash.com/docs/4.17.4#chain
Interestingly, depending on how many elements have flag set, the lodash version is faster. See: jsfiddle.net/1vxac6ex/1. This is looping over 10 million records and setting flag to true when i%10 == 0. If we ALWAYS set flag, then your version is quite a bit faster. The "issue" with your version is that it's setting the property for every item, even when it doesn't need to. Ultimately, I like your version better. Using lodash doesn't make sense, but that's what the OP wanted. ¯_(ツ)_/¯
Wow, very interesting!

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.