user13101751
user13101751

Reputation:

extract values from an object with forEach

I run a graphql query and obtain data (data.personalPlaces), an object that looks like this:

nodes: (4) [{…}, {…}, {…}, {…}]

where each node is like this:

0:
customisedName: "HomeOfBestFriendAlice"
id: 1
placeName: "Husbrok 1, 26127 Oldenburg, Deutschland"
center: "Zes"
__typename: "FavouritePlace"
__proto__: Object

I want to iterate through all nodes such that I can make an array out of it

  favouriteLocations: [
    {
      name: 'Zu Hause',
      street: 'Müllersweg',

    },
    {
      name: 'Büro',
      street: 'Philipp-Reis-Gang',
    },
    {
      name: 'KaffeeHaus',
      street: 'Cloppenburgerstr.',
    },
  ],

where name is the customisedName and street is the placeName from my original data. How can I achieve this?

Data shape:

{
  "data": {
    "personalFavouritePlaces": {
      "nodes": [
        {
          "placeName": "Paris, France"
        },

      ]
    }
  }
}

Upvotes: 0

Views: 627

Answers (1)

gbalduzzi
gbalduzzi

Reputation: 10166

You can use .map() on the array

const favoriteLocations = data.personalFavouritePlaces.nodes.map(node => {
  return {
    name: node.customisedName,
    street: node.placeName
  }
}

Upvotes: 2

Related Questions