1

Can someone help me with the syntax for how to loop through an object literal using jQuery $.each and replace strings that match in each item?

If I have:

var foo = {
    item1: "Mary had a little lamb",
    item2: "Whose fleece was white as snow",
    item3: "Johnny ha a little lamb",
    item4: "What's the deal with lambs?"
}

And I want to replace the word lamb with lion, where inside the $.each function do I replace the item?

I've tried:

$.each(foo, function(key, value){
     return value.replace(/lamb/, "lion");
}

But it doesn't replace the items?

user1837608
  • 930
  • 2
  • 11
  • 37

1 Answers1

0

Use String replace method to replace the text & update the value of the object

var foo = {
  item1: "Mary had a little lamb",
  item2: "Whose fleece was white as snow",
  item3: "Johnny has a little lamb",
  item4: "What's the deal with lambs?"
}
$.each(foo, function(i) {
  foo[i] = foo[i].replace('lamb', 'lion')
});
console.log(foo)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
brk
  • 48,835
  • 10
  • 56
  • 78
  • That did the trick! I didn't realize you could iterate the function using $.each and just the object key (without explicitly noting the value in the function). – user1837608 Jan 27 '18 at 03:15