0

I have been trying to delete a nested object from a JavaScript object, with no success and have not been able to find the correct answer through searching previous posts.

Here is what I have been trying to do.

<code id='code'></code>
var myobj = {
 "children": [
 {
 "name": "albuterol ",
 "children": [
 {
 "name": "albuterol - fluticasone ",
 "children": [
 {
 "name": "prednisone ",
 "children": [
 {
 "name": "dexamethasone ",
 "children": [],
 "size": 1,
 "colname": "CONCEPT_NAME.4"
 }
 ],
 "size": 3,
 "colname": "CONCEPT_NAME.3"
 }
 ],
 "size": 4,
 "colname": "CONCEPT_NAME.2"
 }]}]} 
function deleteObject(myobj) {
 var x = delete myobj.colname
 return (myobj.name, myobj.children)
}
document.getElementById('code').innerText = JSON.stringify(deleteObject(myobj))

I want to delete the object colname. Am I missing something or is the code completely incorrect?

Federico klez Culloca
27.3k17 gold badges61 silver badges102 bronze badges
asked Jun 27, 2018 at 15:37
6
  • myobj does not have a property called colname Commented Jun 27, 2018 at 15:39
  • I am a beginner with JSON. I thought that children, name, size, and colname were objects inside of the JSON. is that incorrect? Commented Jun 27, 2018 at 15:40
  • Do you want to delete every colname? There are many Commented Jun 27, 2018 at 15:42
  • Yes, I would like to delete every colname. Is that impossible? Commented Jun 27, 2018 at 15:43
  • You will need to create a recursive funcion which goes deeper in your array if there is a children prop Commented Jun 27, 2018 at 15:43

2 Answers 2

4

You need a recursive function to delete the property.

var myobj = {
 "children": [
 {
 "name": "albuterol ",
 "children": [
 {
 "name": "albuterol - fluticasone ",
 "children": [
 {
 "name": "prednisone ",
 "children": [
 {
 "name": "dexamethasone ",
 "children": [],
 "size": 1,
 "colname": "CONCEPT_NAME.4"
 }
 ],
 "size": 3,
 "colname": "CONCEPT_NAME.3"
 }
 ],
 "size": 4,
 "colname": "CONCEPT_NAME.2"
 }]}]} 
function deleteColnameRecursive(obj){
 delete obj.colname
 if(obj.children){
 for(var i=0;i<obj.children.length;i++)
 deleteColnameRecursive(obj.children[i]);
 }
}
deleteColnameRecursive(myobj);
console.log(myobj);

answered Jun 27, 2018 at 15:49
Sign up to request clarification or add additional context in comments.

Comments

-3

MyObj does not directly have a property of colname. MyObj has an array named Children.

To delete the proper attribute, select the proper object. For example myObj.children[0].colname

answered Jun 27, 2018 at 15:42

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.