简体   繁体   English

从 api 对象数组生成新的 object

[英]Generating a new object from an api array of objects

What I'm trying to do is take the array of objects that is returned to me from the API and create a new object and then add that object to the employees list.我要做的是获取从 API 返回给我的对象数组,并创建一个新的 object,然后将 object 添加到员工列表中。

I am getting the correct results from the API its just creating a new object from the results and attaching that object to the employeesList array.我从 API 得到正确的结果,它只是从结果中创建一个新的 object 并将 object 附加到 employeesList 数组。

var employeesList = [];

this.getEmployees = function () {
    $http.get("https://randomuser.me/api/?nat=us&results=100&inc=name,location")
    .then(function(response) {
        employees = response.data.results;
        employees.map(employee => {
            return [
                employee.employeeName = employee.name.first + ' ' + employee.name.last, 
                employee.employeeStreet = employee.location.street.number + ' ' + employee.location.street.name,
                employee.employeeCity = employee.location.city,
                employee.employeeState = employee.location.state,
                employee.employeeZipCode = employee.location.postcode,
            ];
        });
    });
    return employeesList;
};

The expected results are an array of employee objects however I am getting an empty array before I even return the employeesList.预期的结果是一个员工对象数组,但是在我返回employeesList 之前我得到了一个空数组。

UPDATE I have the initial problem working however it makes it difficult when I am trying to add or delete an employee.更新我遇到了最初的问题,但是当我尝试添加或删除员工时它变得很困难。

this.addEmployee = function (employee) {
    var employeesList = this.getEmployees();
    employeesList.push(employee);
    var str = JSON.stringify(employeesList);
    localStorage.setItem("Employees", str);
};

this.removeEmployee = function (employee) {
    var employeesList = this.getEmployees();
    employeesList.splice(employeesList.indexOf(employee), 1);
    var str = JSON.stringify(employeesList);
    localStorage.setItem("Employees", str);
};

The code needs to return the $http promise:代码需要返回$http promise:

this.getEmployees = function () {
    var url = "https://randomuser.me/api";
    var params = {
      nat: "us",
      results: 100,
      inc: "name,location"
    };
    var config = { params: params };

    var promise = $http.get(url, config)
    var newPromise = promise.then(function(response) {
        var list = response.data.results;
        var newList = list.map(employee => ({
          employeeName: employee.name.first + ' ' + employee.name.last, 
          employeeStreet: employee.location.street.number + ' ' + employee.location.street.name,
          employeeCity: employee.location.city,
          employeeState: employee.location.state,
          employeeZipCode: employee.location.postcode,
        }));
        return newList;
    });
    return newPromise;
};

Then the calling code needs to extract the data from the promise:那么调用代码需要从promise中提取数据:

var promise = this.getEmployees();

promise.then(list => {
    console.log(list);
    this.employeeList = list;
});

Points to remember:要记住的要点:

  1. The $http service returns a promise $http服务返回 promise
  2. The .then method returns a new promise based on returned values .then方法根据返回值返回一个的 promise
  3. The array.map method returns a new array array.map方法返回一个新数组
  4. Data needs to be extracted from promises需要从 Promise 中提取数据

Following might give you expected list.以下可能会给您预期的清单。

employees.map(employee => {
    employee.employeeName = employee.name.first + ' ' + employee.name.last;
    employee.employeeStreet = employee.location.street.number + ' ' + employee.location.street.name;
    employee.employeeCity = employee.location.city;
    employee.employeeState = employee.location.state;
    employee.employeeZipCode = employee.location.postcode;

    return employee;
});

The success handler of a promise does not have a return value. promise 的成功处理程序没有返回值。

This line creates a global variable called employees.这一行创建了一个名为employees 的全局变量。

employees = response.data.results;

This line creates a new array that is not assigned to anything and falls straight to garbage collection.这一行创建了一个新数组,它没有分配给任何东西,直接进入垃圾收集。

employees.map(employee => { // your map function });

You map function takes each employee and creates an array so you are ending up with an array of arrays.您 map function 获取每个员工并创建一个数组,因此您最终得到一个 arrays 数组。

What you need to do is assign the correct mapping to employeesList in the success handler of the promise after it resolves.您需要做的是在 promise 解析后的成功处理程序中为 employeesList 分配正确的映射。

this.getEmployees = function () {
  $http.get("https://randomuser.me/api/?nat=us&results=100&inc=name,location")
  .then(function(response) {
    employeesList = response.data.results.map(employee => ({
      employeeName: employee.name.first + ' ' + employee.name.last, 
      employee.employeeStreet: employee.location.street.number + ' ' + employee.location.street.name,
      employeeCity: employee.location.city,
      employeeState: employee.location.state,
      employeeZipCode: employee.location.postcode
    }));
  });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM