Tuesday, 15 September 2015

javascript - Manipulating data using JSON parse/stringify -



javascript - Manipulating data using JSON parse/stringify -

i have question manipulating json info using javascript , stringify/parse. in below example, create json string, utilize parse convert object. after doing that, want delete item id, , way can find loop through entire array , delete element array 1 time find match. doesn't seem efficient. there improve way this?

var employees = []; //build array (var i=0; < 10; i++) { var player = { "id": i, "salary": i*1000000 }; employees.push(player); } json_employees = json.stringify({employees: employees}); //convert json string alert(json_employees); //display new string var obj = json.parse(json_employees); //convert javascript object (var j=0; j < obj.employees.length; j++) { // loop through array if (obj.employees[j].id === 5) // employee id 5? obj.employees.splice(j, 1); // remove 5th item } json_modified_employees = json.stringify({employees: obj.employees}); //convert json string alert(json_modified_employees); //display new string

you store employees in object, key of id, this:

// create store object var employees = {}; //build array (var i=0; < 10; i++) { var player = { "id": i, "salary": i*1000000 }; // add together item store object key of 'pk' + employees['pk' + i] = player; } json_employees = json.stringify({employees: employees}); //convert json string alert(json_employees); //display new string var obj = json.parse(json_employees); //convert javascript object // remove required item (in case number 5) delete obj.employees['pk' + 5]; json_modified_employees = json.stringify({employees: obj.employees}); //convert json string alert(json_modified_employees); //display new string

if wanted iterate on employees,

for (var key in employees) { if (employees.hasownproperty(key)) { alert(employees[key].id) } }

javascript json

No comments:

Post a Comment