My promise returns a JSON like this:
‘[ {"amazing data": "hello", "amazing again": "yep"}, {"amazing data": "hello", "amazing again": "yep"}]’
I would just like to return an array of objects:
[
{"amazing data": "hello", "amazing again": "yep"},
{"amazing data": "hello", "amazing again": "yep"}
]
I would like to access it this way because I can work with reduce after the promise returns.
My code:
const amazingPromise = await getData().then((data) => {
return data
})
const prodArray = Array.from(amazingPromise.reduce((acc, o) => {
Object.entries(o)
.forEach(([k, v]) => {
if(!acc.has(k)) acc.set(k, [k])
acc.get(k).push(Array.isArray(v) ? v.join(' | ') : v)
})
return acc
}, new Map()).values())
Any help will be great. Thanks.
If your project is a Web project, you can use react.State() for solve this. For example, in my projects, I use the state to save the results of an API request like your example.
const App = ()=>{
const[array, setArray] = useState([]); //Init the array as a empty array
useEffect( ()=>{
const RequestAPI = async ()=>{
const URL = "https://...";
const response = await fetch(URL);
const newArray = await response.json();
setArray(newArray);
};
RequestAPI();
},[]);
return (
{array.map(item => <ComponentItem /> ) }
}
Try to use something similar to state and async functions in your project as its possible