1

I have a json object , when looped through using a foreach outputs the below :

{"Comment": {"id":"1","post_id":"31","created":"14263241"} , "User": {"fname":"Test","lname":"Test2"} } 

{"Comment": {"id":"2","post_id":"32","created":"14263257"} , "User": {"fname":"Lionel","lname":"Messi"} } 

Where created is a timestamp .

Using a condition from another array , i want to be able to insert a new element in the second array so that it becomes like this :

{"Comment": {"id":"2","post_id":"32","created":"14263257"} , "User": {"fname":"Lionel","lname":"Messi"}, "Status":{"status":"add","userid":"10"} } 

where "Status":{"status":"add","userid":"10"} will be from another json object .

Any help would be appreciated .

0

1 Answer 1

2

I assume your JSON is on the format

var json = [
  {"Comment": {"id":"1","post_id":"31","created":"14263241"} , "User": {"fname":"Test","lname":"Test2"} }, 
  {"Comment": {"id":"2","post_id":"32","created":"14263257"} , "User": {"fname":"Lionel","lname":"Messi"} } 
];

And your "another array" holds an item like this

var otherJson = {"id":"2", "Status":{"status":"add","userid":"10"} } 

Then iterate over each element in the first json and insert Status from otherJson when the criteria match :

for (var index in json) {
    if (json[index].Comment.id == otherJson.id) {
        json[index].Status = otherJson.Status;
    }      
}  

The item with the Comment.id 2 is now enriched with Status.

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

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.