Prozak
Prozak

Reputation: 303

Changing key value of object without discarding rest of keys

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

Answers (3)

mathk
mathk

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

Boney
Boney

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

Jack Bashford
Jack Bashford

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

Related Questions