JSON to dictionary in JavaScript?

前端 未结 4 2135
我在风中等你
我在风中等你 2020-12-31 03:34

In my JS code, I need to convert the JSON response from server to a dictionary so that I can access them by key names. Here is the situation:

Say, this is the JSON r

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-31 04:15

    You could write a javascript function to get an employee by id from a list of employees:

    function getEmployee(id, employees) {
        for (var i = 0; i < employees.length; i++) {
            var employee = employees[i];
            if (employee.id === id) {
                return employee;
            }
        }
    
        return null;
    }
    

    and then use this function on the response you got from the server after parsing the JSON string back to a javascript object:

    var json = 'the JSON string you got from the server';
    var obj = JSON.parse(json);
    var employees = obj.employees;
    var employee = getEmployee(34, employees);
    if (employee != null) {
        alert(employee.name);
    }
    

提交回复
热议问题