简体   繁体   中英

loopback format result in afterRemote hook

I have two models Book.json and Department.json. When I fetch book details, we are also fetching corresponding department through relation. Output is :

[{
"title": "Python",
"department": {
    "name": "Software"
}
},
{
"title": "World",
"department": {
    "name": "Politics"
}
}]

How we can format the above code to

[{
"title": "Python",
"department": "Software"
},
{
"title": "World",
"department": "Politics"
}]

When I tried to format the ctx.result , it gives me an error like only getter is supported.

"message": "Cannot set property books of #ModelConstructor which has only a getter",

You can use Array#map to loop through the items and modify each item in the iteration:

 const data = [{"title":"Python","department":{"name":"Software"}},{"title":"World","department":{"name":"Politics"}}]; const result = data.map(item => { item.department = item.department.name; return item; }); console.log(result); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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