Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
How to extend the response of an api in react by adding a new property based on a condition?

I want to call an API and extend the response by adding a new 'category' prop to each categories ['thirds', 'fifths', 'magic']

  • if the id is divisible by 3 => thirds
  • if the id is divisible by 5 => fifths
  • if the id is divisibly by 3 and 5 => 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}
           
            ))}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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'})
   };
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!