0

我有一个关于使用 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
4

1 回答 1

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)
    }
}
于 2013-02-11T17:39:23.820 回答