Reputation: 303
I would like to replace spaces with underscores for a specific key in all incoming objects. It works, however the rest of the keys dissappear.
The objects:
{
"id": "235",
"reference": "AA",
"name": "Jake H",
},
{
"id": "668",
"reference": "TC",
"name": "Felix S",
}
Actual outcome:
["Jake_H", "Felix_S"]
Method:
import jsonResults from './results.json'
data() {
return {
results: [],
}
},
mounted() {
const filteredResults = jsonResults
// I have other incoming objects that do not have names.
.filter(result => result.name)
.map(
result => result.name.replace(' ', '_')
)
this.results = filteredResults
}
I expect just the key value to change but what happens is the rest of the object is discarded.
Expect
{
"id": "235",
"reference": "AA",
"name": "Jake_H",
}
Actual
["Jake_H"]
Upvotes: 0
Views: 289
Reputation: 8143
You are returning the just the name in the map
funciton:
result => result.name.replace(' ', '_')
So rather do:
result => { result.name = result.name.replace(' ', '_'); return result; }
Upvotes: 0
Reputation: 2202
You need to return other properties as well in the map method, together with the modified name
property.
const filteredResults = jsonResults
.filter(result => result.name)
.map(
result => {
return {
...result,
name: result.name.replace(' ', '_')
}
}
)
Upvotes: 0
Reputation: 44145
You're returning result.name.replace(...)
due to the implicit return of the ES6 arrow function - return result
after modifying it. Destructuring is useful here, as is spreading:
.map(({ name, ...r }) => ({ ...r, name: name.replace(/ /g, "_")));
Alternate way:
.map(result => {
result.name = result.name.replace(/ /g, "_");
return result;
});
Upvotes: 4