代码之家  ›  专栏  ›  技术社区  ›  Sameer

返回新形式的数组-javascript

  •  1
  • Sameer  · 技术社区  · 7 年前

    我的数据:

    {
      "rows": [
        {
          "id": 3,
          "code": "airtel121",
          "position": "manager",
          "salary": "25000",
          "login": {
            "id": 4,
            "username": "sameer",
            "firstName": "Mohamed",
            "lastName": "Sameer",
            "code": "airtel121",
          }
        },
        {
          "id": 7,
          "code": "airtel121",
          "position": null,
          "salary": null,
          "login": {
            "id": 8,
            "username": "annamalai",
            "firstName": "Anna",
            "lastName": "malai",
            "code": "airtel121",
          }
        }
      ]
    }
    

    我的预期结果:

    {
      "rows": [
        {
          "id": 4,
          "username": "sameer",
          "firstName": "Mohamed",
          "lastName": "Sameer",
          "code": "airtel121",
          "staffs": [
            {
              "id": 3,
              "code": "airtel121",
              "position": "manager",
              "salary": "25000",
            }
          ]
        },
        {
          "id": 8,
          "username": "annamalai",
          "firstName": "Anna",
          "lastName": "malai",
          "code": "airtel121",
          "staffs": [
            {
              "id": 7,
              "code": "airtel121",
              "position": null",
              "salary": null",
            }
          ]
        }
      ]
    }
    

    我试过了,但只有我得到了第一个目标,检查我的小提琴:

    http://jsbin.com/qaqehakuwi/edit?js,output

    这是可以循环使用for循环还是可以通过lodash完成?

    检查我上面的jsbin链接中的代码。

    1 回复  |  直到 7 年前
        1
  •  2
  •   ibrahim mahrir    7 年前

    你可以用 map 创建 rows 新对象的数组 旧的数组:

    let newObj = {
      rows: oldObj.rows.map(row => {                                     // map the rows of the old object into the rows of the new object
        let { login, ...rest } = row;                                    // for each object/row get the login object as 'login' and the rest of the props as 'rest'
        return { ...login, staffs: [rest] };                             // return a new object that has the props of 'login' and an additional prop 'staffs' which is an array containing 'rest'
      })
    };
    

    例子:

    let oldObj = {"rows":[{"id":3,"code":"airtel121","position":"manager","salary":"25000","login":{"id":4,"username":"sameer","firstName":"Mohamed","lastName":"Sameer","code":"airtel121"}},{"id":7,"code":"airtel121","position":null,"salary":null,"login":{"id":8,"username":"annamalai","firstName":"Anna","lastName":"malai","code":"airtel121"}}]};
    
    let newObj = {
      rows: oldObj.rows.map(row => {
        let { login, ...rest } = row;
        return { ...login, staffs: [rest] };
      })
    };
    
    console.log(newObj);