使用JSON解析/字符串化处理数据

时间:2013-02-11 17:35:33

标签: javascript json

我有一个关于使用Javascript和stringify / parse操作JSON数据的问题。在下面的示例中,我创建了一个JSON字符串,然后使用parse将其转换回对象。在这样做之后,我想要做的是删除具有特定ID的项目,我能找到的唯一方法是遍历整个数组并在找到匹配后从数组中删除元素。这看起来效率不高。有更好的方法吗?

var employees = [];

//build the array
for (var i=0; i < 10; i++) {
    var player = { "id": i, "salary": i*1000000 };
    employees.push(player);
}

json_employees = JSON.stringify({employees: employees}); //convert to json string
alert(json_employees); //display the new string

var obj = JSON.parse(json_employees); //convert back to a Javascript object

for (var j=0; j < obj.employees.length; j++) { // loop through the array
    if (obj.employees[j].id === 5) // is it the employee with id 5?
        obj.employees.splice(j, 1); // remove the fifth item
}

json_modified_employees = JSON.stringify({employees: obj.employees}); //convert back to json string
alert(json_modified_employees); //display the new string

1 个答案:

答案 0 :(得分:0)

您可以将员工存储在一个对象中,其密钥为id,如下所示:

// create a store object
var employees = {};

//build the array
for (var i=0; i < 10; i++) {
    var player = { "id": i, "salary": i*1000000 };
    // add item to store object with a key of 'pk' + i
    employees['pk' + i] = player;
}

json_employees = JSON.stringify({employees: employees}); //convert to json string
alert(json_employees); //display the new string

var obj = JSON.parse(json_employees); //convert back to a Javascript object

// remove the required item (in this case number 5)
delete obj.employees['pk' + 5];

json_modified_employees = JSON.stringify({employees: obj.employees}); //convert back to json string
alert(json_modified_employees); //display the new string

如果您想迭代您的员工,那么

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