1

I have an array of objects. If I do a console.log, I see this data.

[Object,Object,Object]
0: Object
  Name: Ria
  Age: 27
  Job: Analytics & Review

1: Object
  Name: Brian
  Age: 23
  Job: Admin

2: Object
  Name: Rick
  Age: 32
  Job: Analytics & Review

As you can see at the Job part, I have & symbol. I want to replace that & with & since html does not allow & to pass directly through ajax since its a reserved entity.

Can someone let me know how I can replace & with & wherever they exist.

3
  • sorry, we cant see what you want to replace & with (you'll have to put it in the grave marks ` so we can see it), and what have you tried so far? Commented Mar 31, 2016 at 17:55
  • 1
    stackoverflow.com/questions/6807180/… Commented Mar 31, 2016 at 18:04
  • can you provide sample how you want use this object, and show why & should be encoded? Commented Mar 31, 2016 at 18:10

2 Answers 2

2

You can replace it

var data = [{ Name: 'Ria', Age: 27, Job: 'Analytics & Review'}, 
            { Name: 'Brian',  Age: 23,  Job: 'Admin'}, 
            { Name: 'Rick', Age: 32, Job: 'Analytics & Review'}]; 

data.forEach(function(currentValue, index, array) { 
    array[index] = JSON.parse(JSON.stringify(array[index]).replace('&', '&amp')); 
});
Sign up to request clarification or add additional context in comments.

4 Comments

why needed JSON.parse(JSON.stringify(?
@Grundy because of replace method... you can use replace only with strings. If you want to replace '&' wherever they exist, you have to do it with strings. After that, you need to parse string in to json and replace old object in array.
so, why not just convert to string if needed, or even do replace if currentValue is srting?
@Grundy currentValue is not a string. It is an object. To convert object to string needed use JSON.stringify method. You can use currentValue instead array[index] it doesn't matter.
1

Idea is to convert your entire array of object into string and then use regex to replace the symbol and then parse back the array of objects back from the string. Try this.

var newArray = JSON.parse(JSON.stringify(array).replace(/&/g,'&amp'));

Comments

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.