Home > database >  Is this valid when it comes to setting something from an API response in React ? (How do I change da
Is this valid when it comes to setting something from an API response in React ? (How do I change da

Time:12-22

I have an API giving me response like this:

[
{id:1, name:mango, flag: true},
{id:2, name:apple, flag: false},
{id:3, name:banana, flag: false},
{id:4, name:peach, flag: false},
{id:5, name:orange, flag: true},
]

Here I have already got the response from the API and stored it in a state value called "getFruits" and then I am trying to modify the data.

I want this API response but want to change the second field from "name" to "fruitname" - How do i do it ? I tried something like this but i think it is wrong.

const [getFruits, setFruits] = useState([]); 

const fruitdata = getFruits.map((data) =>   { 
id: data.id;
fruitname: data.name;
flag: data.flag;   }   );

In the end, I want a new JSON which will be like this:

[
{id:1, fruitname:mango, flag: true},
{id:2, fruitname:apple, flag: false},
{id:3, fruitname:banana, flag: false},
{id:4, fruitname:peach, flag: false},
{id:5, fruitname:orange, flag: true},
]

Additionally, If i want to filter this, like a. Get all the "false" line items only b. Get ID with 4 ..and then assign it to a a new JSON constant, how do i do it ? like fruitfilteredtrue giving me the below:

[
 {id:1, fruitname:mango, flag: true},
 {id:5, fruitname:orange, flag: true},
]

Update: I think it should not be const moreover.

I tried something like this but when doing this, the return data does not look like.. every line in the JSON gets enclosed by a fielddata

fielddata = getFields.map((data) => {
  return (
    { 
      id: data.id,
      fruitname: data.name,
      flag: data.flag
    }
  )
  });

CodePudding user response:

You miss the return statement.

const fruitdata = getFruits.map((data) => { 
     return {
         id: data.id;
         fruitname: data.name;
         flag: data.flag;
     }
});

This is my working example -

const rawData =[
  {id:1, name:"mango", flag: true},
  {id:2, name:"apple", flag: false},
  {id:3, name:"banana", flag: false},
  {id:4, name:"peach", flag: false},
  {id:5, name:"orange", flag: true},
  ]
  
const [getFruits, setFruits] = useState([]); 
useEffect(()=>{
    setFruits(rawData)
},[]);

const fruitdata = getFruits.map((data) => { 
const newObj = {};
newObj.id = data.id;
newObj.fruitname = data.name;
newObj.flag= data.flag;
return newObj;
});

console.log(fruitdata)
  • Related