foreach js重新格式化数据

时间:2018-04-16 21:38:38

标签: javascript foreach

我正在创建一个rest API,我从我的一个请求中获取数据 但我想解析他们

我尝试创建一个foreach循环,但每行都得到相同的结果 那里 是我的数据样本

      result = [
    {
        "id": 1,
        "UserID": 2,
        "idFriend": 3,
        "status": "pending",
        "UserId": 2,
        "User": {
            "id": 2,
            "email": "toto@gmail.com",
            "username": "tetar",
            "isAdmin": false,
            "isOut": false,
            "bio": null,
        }
    },
    {
        "id": 2,
        "UserID": 2,
        "idFriend": 1,
        "status": "pending",
        "UserId": 2,
        "User": {
            "id": 2,
            "email": "toto@gmail.com",
            "username": "tetar",
            "isAdmin": false,
            "isOut": false,
            "bio": null,
        }
    },
]

我希望修改我的数据

`result = [{
  "id"= 1,
  "User": {
        "id": 2,
        "email": "toto@gmail.com",
        "username": "tetar"
     }
  },
  {
  "id"= 2,
  "User": {
        "id": 2,
        "email": "titi@gmail.com",
        "username": "tetar"
     }
    }
  }]`
你知道我怎么办? 很多

2 个答案:

答案 0 :(得分:2)

只是一个映射功能。

const newResult = [];

result.forEach((r) => {
  newResult.push({
    id: r.id,
    user: {
      id: r.User.id,
      email: r.User.email,
      username: r.User.username
    }
  });
});

console.log(newResult);

我非常确定有更好的清洁和更高效的方法来做到这一点。我建议使用lodash map函数:

https://lodash.com/docs/4.17.5#map

答案 1 :(得分:1)

您可以使用Array.prototype.map:



result = [
    {
        "id": 1,
        "UserID": 2,
        "idFriend": 3,
        "status": "pending",
        "UserId": 2,
        "User": {
            "id": 2,
            "email": "toto@gmail.com",
            "username": "tetar",
            "isAdmin": false,
            "isOut": false,
            "bio": null,
        }
    },
    {
        "id": 2,
        "UserID": 2,
        "idFriend": 1,
        "status": "pending",
        "UserId": 2,
        "User": {
            "id": 2,
            "email": "toto@gmail.com",
            "username": "tetar",
            "isAdmin": false,
            "isOut": false,
            "bio": null,
        }
    },
]
let out = result.map(el=>{return {id: el.id, User:{id: el.User.id, email: el.User.email, username:el.User.username}}});
console.log(out);