i am creating a rest API and i get data from one of my request but i want to parse them
i try to create a foreach loop but a get in every line the same result there is a sample of my data
result = [
{
"id": 1,
"UserID": 2,
"idFriend": 3,
"status": "pending",
"UserId": 2,
"User": {
"id": 2,
"email": "[email protected]",
"username": "tetar",
"isAdmin": false,
"isOut": false,
"bio": null,
}
},
{
"id": 2,
"UserID": 2,
"idFriend": 1,
"status": "pending",
"UserId": 2,
"User": {
"id": 2,
"email": "[email protected]",
"username": "tetar",
"isAdmin": false,
"isOut": false,
"bio": null,
}
},
]
and i want to get my data modifed like
`result = [{
"id"= 1,
"User": {
"id": 2,
"email": "[email protected]",
"username": "tetar"
}
},
{
"id"= 2,
"User": {
"id": 2,
"email": "[email protected]",
"username": "tetar"
}
}
}]`
do you know how can i do it ? thx a lot
asked Apr 16, 2018 at 21:38
tetar
8921 gold badge11 silver badges28 bronze badges
-
Where's your code? Stackoverflow isn't a free code writing service....or a "how to" tutorial service. You are expected to show your attempts to solve issues yourself and people help you fix your codecharlietfl– charlietfl2018年04月16日 21:48:52 +00:00Commented Apr 16, 2018 at 21:48
-
i just past 2 hour to deal with this issue and in 3 min in Stackoverflow someone give me the solution. i think the purpose of this web site is to help each other.tetar– tetar2018年04月16日 21:53:30 +00:00Commented Apr 16, 2018 at 21:53
-
No...that is not how it is supposed to work. Take some time to read help centercharlietfl– charlietfl2018年04月16日 22:08:13 +00:00Commented Apr 16, 2018 at 22:08
2 Answers 2
Just a mapping function.
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);
I am pretty sure there are better cleaner and more performant ways to do this. I recommend using lodash map function:
answered Apr 16, 2018 at 21:43
gaheinrichs
6101 gold badge6 silver badges13 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You can use Array.prototype.map:
result = [
{
"id": 1,
"UserID": 2,
"idFriend": 3,
"status": "pending",
"UserId": 2,
"User": {
"id": 2,
"email": "[email protected]",
"username": "tetar",
"isAdmin": false,
"isOut": false,
"bio": null,
}
},
{
"id": 2,
"UserID": 2,
"idFriend": 1,
"status": "pending",
"UserId": 2,
"User": {
"id": 2,
"email": "[email protected]",
"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);
answered Apr 16, 2018 at 21:44
Randy Casburn
14.2k1 gold badge20 silver badges32 bronze badges
Comments
lang-js