I'm fetching data from API and i would like to add property to my object. I'm currently adding image property but i need to add this one layer deeper inside object.
Could you give me a hint how to achieve that?
My code:
const Review = () => {
const url = "https://jsonplaceholder.typicode.com/users";
const [people, setPeople] = useState(null);
const fetchPeople = async () => {
try {
const response = await fetch(url);
const data = await response.json();
let test = Object.entries(data).map((people) => ({
...people,
image: "image url goes here",
}));
setPeople(test);
} catch (error) {
console.error(error);
}
};
useEffect(() => {
fetchPeople();
console.log(people);
}, []);
Object.entries returns an array [index, value]. You just need to add image property to value which is an object.
fetch("https://jsonplaceholder.typicode.com/users").then(r => r.json()).then(data => { const newData = Object.entries(data).map(people => { people[1].image = "some image here" return people; }); console.log(newData); });
Using object.entries was bad idea:D Solution for my question is:
const fetchPeople = async () => {
try {
const response = await fetch(url);
const data = await response.json();
const peopleWithImages = data.map((person, index) => {
return {
...person,
image: `https://robohash.org/?set=set${index + 1}`,
};
});
setPeople(peopleWithImages);
} catch (error) {
console.error(error);
}
};
useEffect(() => {
fetchPeople();
}, []);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.