0

I am trying to figure out how to remove a key called age from an array.

I tried below splice, but didnt help me removing the key and retain other keys and values in an array.

$(data).splice("age",1);

Here is my full code that outputs an array

var data = {'fname': 'John', 'lname': 'Smith', 'age': 29, 'job': 'Agent' };

$(data).splice("age",1);

console.log(data);

Here is JSFiddle link that demonstrates above example.

Ray
  • 1,095
  • 3
  • 18
  • 43

2 Answers2

0

You can use delete data.age; to remove your item from the object in JavaScript.

It seems like you were thinking of the object more like an array, whereas objects get special treatment in JavaScript.

Maximillian Laumeister
  • 19,884
  • 8
  • 59
  • 78
  • Thank you. :) That works for sure. But I am trying to figure it out how I can accomplish this with pure JQuery. – Ray Aug 14 '15 at 01:45
  • @Ray Pardon for asking, but why do you want to use jQuery for this when the JavaScript is already a one-liner? – Maximillian Laumeister Aug 14 '15 at 01:46
  • I have heard from others that some users dont have javascript enabled and delete might not work. Correct me if I am wrong :) – Ray Aug 14 '15 at 01:49
  • 1
    @Ray jQuery is a JavaScript framework, so if your users have JavaScript disabled, jQuery will not run. – Maximillian Laumeister Aug 14 '15 at 01:50
  • gotcha... in that case there is no point for me spending more time on when JavaScript can do a fine job with one line. – Ray Aug 14 '15 at 01:53
0

Use delete like

var data = {'fname': 'John', 'lname': 'Smith', 'age': 29, 'job': 'Agent' };
delete data.age;
console.log(data);
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
  • Thanks AmmarCSE, That does the trick. However, I am trying to figure out this with pure JQuery and not using delete from javascript which may not be available in all browsers. – Ray Aug 14 '15 at 01:47