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."
]
}
CodePudding user response:
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()
and Object.fromEntries()
to disassemble and reassemble the object:
const data = {
id: 1,
name: 'Lorem ipsum',
state_id: 14
};
const fn = (x) => Object.fromEntries(Object.entries(x).map(([k, v]) => [k.endsWith('_id') ? k.slice(0, -3) : k, v]));
console.log(fn(data));
You can shorten it a little more by using replace()
with a regex:
const data = {
id: 1,
name: 'Lorem ipsum',
state_id: 14
};
const fn = (x) => Object.fromEntries(Object.entries(x).map(([k, v]) => [k.replace(/_id$/, ''), v]));
console.log(fn(data));
If you use lodash, you can go shorter still by using the mapKeys()
function:
const data = {
id: 1,
name: 'Lorem ipsum',
state_id: 14
};
const fn = (x) => _.mapKeys(x, (v, k) => k.replace(/_id$/, ''));
console.log(fn(data));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>