1

Suppose I have a JSON array like:

[{
    "box": "box1",    
    "parent": [{
        "id": "box0"
    }],
    "child": [{
        "id": "box2"
    }]
},{
    "box": "box2",
    "parent": [{
        "id": "box1"
    }],
    "child": [{
        "id": "box3"
    },{
        "id": "box4"
    }]
}]

Now assume that I want to change a value parent id of box2 then how do I do that.

How can I specifically change a particular value?

2
  • What about deserializing this JSON string to an object, change the value in the object and then serializing this object ? Commented Oct 7, 2015 at 7:42
  • Any example would help Commented Oct 7, 2015 at 7:43

2 Answers 2

1

var arr = [{
  'box': 'box1',
  'parent': [{
    'id': 'box0'
  }],
  'child': [{
    'id': 'box2'
  }]
}, {
  'box': 'box2',
  'parent': [{
    'id': 'box1'
  }],
  'child': [{
    'id': 'box3'
  }, {
    'id': 'box4'
  }]
}];

arr = arr.map(function(box) {
   if (box.box === 'box2') {
     box.parent = [{ id: 'box0' }];
   }
  
   return box;
      
});

console.log(arr);

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the quick reply. But this is to add a new value. I also would like to edit existing value and delete a particular value.
You could already do anything with the filtered box object. Don't rely on SO for everything you need to do.
0

You can deserialize this JSON string into a javascript object, modify the property in the object and then serializing the javascript object into a JSON string :

var json = '[{"box":"box1","parent":[{"id":"box0"}],"child":[{"id":"box2"}]},{"box":"box2","parent":[{"id":"box1"}],"child":[{"id":"box3"},{"id":"box4"}]}]';
var obj = JSON.parse(json);
obj[1].parent[0].id = "whatever";
var newjson = JSON.stringify(obj);

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.