I want to call an API and extend the response by adding a new 'category' prop to each categories ['thirds', 'fifths', 'magic']
The url is https://jsonplaceholder.typicode.com/posts
How do i do that?
async function getData() {
const response = await fetch("https://jsonplaceholder.typicode.com/posts");
const data = await response.json();
}
{contacts.map((contact) => (
{contact.id}
{contact.userId}
{contact.title}
{contact.body}
))}
To check if a number (x) is divisible by a number (N) we use a modulo operator (%), which returns the rest of a division, so eg. if x=5 and N=2 then x%N=1, because 5%2=1 (5/2=2+1).
So in your case you indeed can use a map function and add a property to your object conditionally, based on the result of according modulo operation result:
contacts.map(contact => {
return {
...contact,
...((contact.id%3===0 && contact.id%5!=0) &&
{category: 'thirds'}),
...((contact.id%3!=0 && contact.id%5===0) &&
{category: 'fifths'}),
...((contact.id%3===0 && contact.id%5===0) &&
{category: 'magic'})
};
});