0

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.

Patrick
  • 3,938
  • 6
  • 20
  • 32
  • 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? – indubitablee Mar 31 '16 at 17:55
  • 1
    http://stackoverflow.com/questions/6807180/how-to-escape-a-json-string-to-have-it-in-a-url – Gene R Mar 31 '16 at 18:04
  • can you provide sample how you want use this object, and show why `&` should be encoded? – Grundy Mar 31 '16 at 18:10

2 Answers2

1

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')); 
});
Grundy
  • 13,356
  • 3
  • 35
  • 55
  • why needed `JSON.parse(JSON.stringify(`? – Grundy Mar 31 '16 at 18:19
  • @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. – Pavel Evdokimov Mar 31 '16 at 18:27
  • so, why not just convert to string if needed, or even do replace if `currentValue` is srting? – Grundy Mar 31 '16 at 18:44
  • @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. – Pavel Evdokimov Mar 31 '16 at 18:52
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'));

Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59