Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
94
rated 0 times [  101] [ 7]  / answers: 1 / hits: 94758  / 9 Years ago, fri, february 20, 2015, 12:00:00

I have the following JSON object data returned from my apicontroller :


[  
{"id":2,"text":"PROGRAMME","parent":null},
{"id":3,"text":"STAGE","parent":2},
{"id":4,"text":"INFRA","parent":2},
{"id":5,"text":"SYSTEM","parent":3},
{"id":6,"text":"STOCK","parent":3},
{"id":7,"text":"DPT","parent":3},
{"id":9,"text":"EXTERNAL","parent":null}
]

I want to replace "parent":null with "parent":'"#"'


I have tried the code below, but it is only replacing the first occurrence of "parent":null. How can I replace all "parent":null entries?


$(document).ready(function () {
$.ajax({
url: "http://localhost:37994/api/EPStructures2/",
type: "Get",
success: function (data) {
var old = JSON.stringify(data).replace(null, "'#'"); //convert to JSON string
var new = JSON.parse(old); //convert back to array
},
error: function (msg) { alert(msg); }
});
});

Thanks,


More From » arrays

 Answers
33

You need to make the replace global:



var old = JSON.stringify(data).replace(/null/g, '#'); //convert to JSON string
var newArray = JSON.parse(old); //convert back to array


This way it will continue to replace nulls until it reaches the end



Regex docs:



https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp



Also, as a side note, you should avoid using new as a variable name as it is a reserved word in javascript and most browsers will not allow you to use it


[#67730] Thursday, February 19, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tayla

Total Points: 681
Total Questions: 102
Total Answers: 108

Location: Marshall Islands
Member since Tue, Sep 21, 2021
3 Years ago
tayla questions
Fri, Mar 5, 21, 00:00, 3 Years ago
Wed, Oct 28, 20, 00:00, 4 Years ago
Thu, Apr 9, 20, 00:00, 4 Years ago
;