admin 管理员组

文章数量: 1086019

var myJsonObj = {"employees":[{"name":"John", "lastName":"Doe", "age": 55},{"name":"Jane", "lastName":"Doe", "age":69}]};

How can I delete myJsonObj.eployees[1] ?

Thank you :)

var myJsonObj = {"employees":[{"name":"John", "lastName":"Doe", "age": 55},{"name":"Jane", "lastName":"Doe", "age":69}]};

How can I delete myJsonObj.eployees[1] ?

Thank you :)

Share Improve this question edited Dec 27, 2011 at 17:36 Rob W 349k87 gold badges807 silver badges682 bronze badges asked Feb 15, 2010 at 7:15 jack moorejack moore 2,0595 gold badges26 silver badges22 bronze badges 1
  • 3 Note: There is no such thing as a JSON object, JSON is a data interchange format. That's just a regular object. – Guffa Commented Feb 15, 2010 at 8:01
Add a ment  | 

3 Answers 3

Reset to default 5
delete myJsonObj.employees[1];

However, this will keep the index of all the other elements. If you want to re-order the index, too, you could use this:

// store current employee #0
var tmp = myJsonObj.employees.shift();
// remove old employee #1
myJsonObj.employees.shift();
// re-add employee #0 to the start of the array
myJsonObj.employees.unshift(tmp);

Or you use simply Darin Dimitrov's splice solution (see his answer below).

myJsonObj.employees.splice(1, 1);

Use delete:

delete myJsonObj.employees[1] 

or set it to null

myJsonObj.employees[1] = null;

Neither will affect the indices of any elements following the element deleted from an array.

本文标签: arraysJavaScriptPrototypejs Delete property from JSON objectStack Overflow