0

Folks, I have the following JSON object, in which I would like to recursively find every occurrence of foo with bar.

Also the [Object] can potentially contain foo which would also need to be replaced.

{ _id: 530797d8952e10129f97fde3,
  Product: 'something',
  Realm: [ 'something', 'something','foo' ],
  Service: 'Node',
  Owners: [ 'foo', 'something' ],
  Project: 'something',
  URLs:
    [ { 'foo': [Object] },
      { 'foo': [Object] },
      { 'foo': [Object] } ] }

How would i loop through this? I've tried with but failed:

var cleanObject = {}
for (key in dirtyObject) {
    key = key.replace('foo', 'bar');
    cleanObject[key] = dirtyObject[key];
}
1
  • Your title mentions recursion (which seems reasonable) but the code you show doesn't include any. Are you asking how to do recursion? Or is there more code that you haven't shown. Commented Feb 21, 2014 at 18:34

1 Answer 1

3

Tip: That's not a "JSON object". There is no such thing as a "JSON object". "JSON" is a string, representing an object. What you have there is an object literal.

However, JSON can help. Consider trying:

var cleanObject = JSON.parse(JSON.stringify(dirtyObject).replace(/foo/g,'bar'));
Sign up to request clarification or add additional context in comments.

7 Comments

That will replace in both keys and values. If I'm reading the question correctly, the OP only wants to replace keys.
@StephenThomas True. But I'm reading the question as "every occurrence", and the code as a botched attempt to do so that only replaces keys. The question is ambiguous as to that point...
gotta agree. not sure what the OP really wants here
Essentially I want EVERY occurrence to be replaced, thanks guys
And your result worked. Wish I could award more points to your solution. This solves a ton of work for me. Thanks
|

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.