0

I'm very beginner in coding. Please help me with this: I need to add an attribute 'name' to my array. I got each element separately but don't know how to add attribute "name" to it :/ is it possible ? Working with graphql an TS, I got this:
"myTypes": [ "cat", "dog", "bird", "butterfly" ]

and I need to become it like this : "myTypes": [ {name: "cat"}, {name:"dog"}, {name: "bird"}, {name: "butterfly"}]

My code: const mydata = response.data.myTypes let names = Array.from(mydata).forEach((element: any) => console.log(element))

thanks for your help !

3
  • You can use mydata.map() to change the strings into objects. Commented Jul 29, 2022 at 10:27
  • You could probably find what you are looking to by looking into Array.map(). Like myData.map(e=>{return {name: e}}) or similar. Commented Jul 29, 2022 at 10:27
  • mydata should already an array so Array.from(mydata) is unnecessary. Have a look at Array.prototype.map(). Commented Jul 29, 2022 at 10:27

1 Answer 1

1

You can use the map function it takes a callback that returns the new array with the modifications you made inside the map. Also your callback should return the new array item everytime it should be like this

const myNewTypes=myTypes.map((type)=>{return { name: type }})
Sign up to request clarification or add additional context in comments.

2 Comments

oh yes It's working !! thank you very much ! I tried it before, but my syntaxe was wrong... thanks a lot :)
Would appreciate if you accept my answer :D

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.