1

I have json like this:

json = [ 
   { 
      "value1":"3863",
      "value2":"4567"
   },
   { 
      "value1":"4456",
      "value2":"87687"
   },
   { 
      "value1":"98494",
      "value2":"4534"
   },   
]

What I need is to delete value2 so the json would look like:

json = [ 
   { 
      "value1":"3863"
   },
   { 
      "value1":"4456"
   },
   { 
      "value1":"98494"
   },   
]

I have tried to use

for(var i = 0; i < json.length; i++)
{    
  delete json["value2"];   
}

but it doesn´t work.

Is there any way of doing that ?

3
  • 1
    delete json[i]["value2"];. I would prefer const result = json.map(({ value1 }) => ({ value1 })); though. Commented Sep 30, 2019 at 15:20
  • 1
    You are missing index 'i'; delete json[i]['value2'] Commented Sep 30, 2019 at 15:22
  • Thanks everyone, it works fine with both options. json.map and with the one I was trying to use (delete) in which I was missing the index i. Commented Sep 30, 2019 at 15:30

5 Answers 5

1

const json = [ 
   { 
      "value1":"3863",
      "value2":"4567"
   },
   { 
      "value1":"4456",
      "value2":"87687"
   },
   { 
      "value1":"98494",
      "value2":"4534"
   },   
];

json.forEach(item => delete item.value2);
Sign up to request clarification or add additional context in comments.

Comments

0

use map.

json = [ 
  { 
     "value1":"3863",
     "value2":"4567"
  },
  { 
     "value1":"4456",
     "value2":"87687"
  },
  { 
     "value1":"98494",
     "value2":"4534"
  }
];

console.log(json.map(({value1}) => ({value1})));

Comments

0

With your current syntax:

for(var i = 0; i < json.length; i++)
{    
  delete json[i].value2;   
}

Comments

0

You just have missed i usage in accessing json array elements:

for(var i = 0; i < js.length; i++)
{    
  delete json[i]["value2"];   
}

Comments

0

You forgot the iterator i:

delete json[i]["value2"];

var json = [ 
   { 
      "value1":"3863",
      "value2":"4567"
   },
   { 
      "value1":"4456",
      "value2":"87687"
   },
   { 
      "value1":"98494",
      "value2":"4534"
   },   
];

for(var i = 0; i < json.length; i++) {    
  delete json[i]["value2"];   
}

console.log(json);

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.