1

I'm remapping JSON objects received from an API which works perfectly. The issue is instead of pushing into a single array searchResultsReFormat, in the console it reads the same line multiple times but with different values.

  searchResultsReFormat: any = [];
  this.searchResults.map(result => {
                const customer  = result.customer
                const meals = result.meals
                const newResults = [{
                  firstName : customer.firstName,
                  lastName : customer.lastName,
                  grade: this.gradeName,
                  meals: [meals]
                }]
                console.log(newResults)
                this.searchResultsReFormat = newResults
              })

enter image description here

but It all should have been grouped inside one single array searchResultsReFormat and when expanded, the data will be showing

1
  • 2
    Are you sure you didn't miss what .map actually do? Commented Aug 6, 2019 at 13:18

2 Answers 2

2

map is actually meant to return a new array by transforming each value according to the callback provided.

You don't need to push or do things, you just need to:

  • Assign the result of map to the desired value.
  • return inside the callback the transformed value.

// assignment here

this.searchResultsReFormat = this.searchResults.map(result => {
  //                                                ^--- callback here
  const customer  = result.customer;
  const meals = result.meals;
  const newResults = [{
    firstName : customer.firstName,
    lastName : customer.lastName,
    grade: this.gradeName,
    meals: [meals]
  }];
  return newResults; // <-- return here.
});
Sign up to request clarification or add additional context in comments.

Comments

1

You need to return the object within map and assign the map results to the array you want.

searchResultsReFormat: any = [];
  this.searchResultsReFormat = this.searchResults.map(result => {
                const customer  = result.customer
                const meals = result.meals
                return {
                  firstName : customer.firstName,
                  lastName : customer.lastName,
                  grade: this.gradeName,
                  meals: [meals]
                }                
              })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.