返回新形式的数组-JavaScript

时间:2018-09-26 15:09:19

标签: javascript arrays json object

我的数据:

{
  "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链接以获取代码。

我在项目中使用ES6编码方式,所以我使用了散布运算符。

1 个答案:

答案 0 :(得分:2)

您可以使用map从旧对象的rows数组创建新对象的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);