H Varma H Varma - 2 months ago 9
JSON Question

How to delete key in object and replace with its value?

I have a sample json like

var obj={
"results":{
"grade":"A",
"marks":12
},
"data":{
"name":"sam",
"gender":"male",
"age":10
}
};


Now I want to transform above json to:

var obj={
"results":{
"grade":"A",
"marks":12
},
"name":"sam",
"age":10
}


I was using for each loop

for(var exKey in obj) {
if(exKey=='data'){
//replace key data with its value
}
}


But I was unable to figure out the logic which would do this.
So can someone help me here how can I achieve this?
Thanks for all ur response,
But if iam having some complicated json like:

var obj={
"results":{
"grade":"A",
"res":"fail",
"marks":12
},
"data":{details:{"name":"sam",
"gender":"male",
"age":10
}
},
"feespaid":"yes",
"joindate":"sunday"


};

Now if I want to modify or delete some keys inside a key value,some thing like

var obj={
"results":{
"grade":"A",
"marks":12
},
"data":{details:{"name":"sam",
"age":10
}
},
"joindate":"sunday"
};


So how we go inside the json and delete

Answer

Use inner for-in loop and use bracket-notation to assign variable as key of object

var obj = {
  "results": {
    "grade": "A",
    "marks": 12
  },
  "data": {
    "name": "sam",
    "gender": "male",
    "age": 10
  }
};
for (var exKey in obj) {
  if (exKey == 'data') {
    for (var d in obj.data) {
      if (d != 'gender') obj[d] = obj.data[d];
    }
    delete obj.data;
  }
}
console.log(obj);

Edit: Only to delete few keys from Object, use delete keyword

var obj = {
  "results": {
    "grade": "A",
    "res": "fail",
    "marks": 12
  },
  "data": {
    details: {
      "name": "sam",
      "gender": "male",
      "age": 10
    }
  },
  "feespaid": "yes",
  "joindate": "sunday"
};
delete obj.results.res;
delete obj.data.details.gender;
delete obj.feespaid;
console.log(obj);