使用ES6 lodash从API的映射对象键
我正在使用VUE 3将帖子数据发送到我的API。对象看起来像
const externalResults: ref(null)
const resource = ref({
id: null,
name: null,
state: {}
})
在将数据发送到API之前,我要解析Resource
对象,以避免发送与state> State
属性相关的嵌套对象。 已发送的有效载荷看起来像
{
id: 1,
name: 'Lorem ipsum',
state_id: 14
}
API在缺少/错误的数据时返回422
{
"message":"Some fields are wrong.",
"details":{
"state_id":[
"The state_id field is mandatory."
]
}
}
因此, 代码>来自键?
由于我使用的是Vuelate,因此我必须将返回的错误详细信息映射到模型属性名称。现在,我正在这样做以获取详细信息后,
externalResults.value = e.response.data.details
我可能需要像1行解决方案一样
externalResults.value = e.response.data.details.map(item => { // Something here... })
但是无论它使用ES6还是Lodash, 。 请注意,state_id
只是一个示例,将有许多属性以_id
结尾,我需要删除。
预期的结果是
externalResults: {
"state":[
"The state_id field is mandatory."
]
}
I'm using Vue 3 for sending POST data to my API. The objects look like
const externalResults: ref(null)
const resource = ref({
id: null,
name: null,
state: {}
})
Before sending the data to the API I'm parsing the resource
object to avoid sending a nested object related to state
property. So the payload sent looks like
{
id: 1,
name: 'Lorem ipsum',
state_id: 14
}
The API returns a 422 in case of missing/wrong data
{
"message":"Some fields are wrong.",
"details":{
"state_id":[
"The state_id field is mandatory."
]
}
}
So here comes the question: how can I rename object keys in order to remove always the string _id
from keys?
Since I'm using vuelidate I have to "map" the returned error details to model property names. Now I'm doing this to get details once the request is done
externalResults.value = e.response.data.details
but probably I will need something like
externalResults.value = e.response.data.details.map(item => { // Something here... })
I'd like to have a 1 line solution, no matter if it uses ES6 or lodash.
Please note that state_id
is just a sample, there will be many properties ended with _id
which I need to remove.
The expected result is
externalResults: {
"state":[
"The state_id field is mandatory."
]
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道您允许您的单线工作多长时间,但这是我在ecmascript中提出的,使用
object.entries()
and object.fromentries()< /代码>拆卸并重新组装对象:您可以通过将
replace()
用正则缩短一点:如果使用lodash,则可以使用
mapkeys() >
功能:
I don't know how long you allow your one-liners to be, but this is what I come up with in ECMAScript, using
Object.entries()
andObject.fromEntries()
to disassemble and reassemble the object:You can shorten it a little more by using
replace()
with a regex:If you use lodash, you can go shorter still by using the
mapKeys()
function: