How can I add this arrayOfObjects to the data that is coming from the api response ?
I tried this pattern but didn't work for me
const url = "https://jsonplaceholder.typicode.com/users";
useEffect(() => {
const arrayOfObjects = [
{num:1},
{num:2},
{num:3},
{num:4},
{num:5},
{num:6},
{num:7},
{num:8},
{num:9},
{num:10},
];
axios(url).then((res) => {
const newData = res.data.map((item) => (item.arrayOfObjects.map(innerItem => innerItem) = num));
console.log(newData);
});
}, []);
for example the result should look like this in the response data although "https://jsonplaceholder.typicode.com/users" has 10 objects
[
{
name: "Leanne Graham"
num: 1
etc.
},
{
name: "Ervin Howell"
num: 2
etc.
},
{ name: "Clementine Bauch"
num: 3
etc.
}
etc.
]
CodePudding user response:
The question is not very clear to me. If what you are trying to do is to combine the data from the API call with the data from arrayOfObjects
into a single array, and then map that into an array of objects with just the name
and num
properties, you could do something like this:
axios.get(url)
.then((res) => {
const dataFromApi = res.data
// this creates a new array which combines the array from the API call with the array in your component's local state
const additionalData = [...dataFromApi, ...arrayOfObjects]
// this creates a new array from the combined array which only has `name` and `num`
const newData = additionalData.map(datum => ({
name: datum.name,
num: datum.num
}))
console.log(newData)
})
If you just want to add a num
to the API response where num
=== id
you can do this:
axios.get(url)
.then(({ data }) => data.map(datum => ({
...datum,
num: datum.id
})))
CodePudding user response:
If I understand your question correctly, you want to add property num for every object in the API data array. This should do it:
useEffect(() => {
const arrayOfObjects = [
{ num: 1 },
{ num: 2 },
{ num: 3 },
{ num: 4 },
{ num: 5 },
{ num: 6 },
{ num: 7 },
{ num: 8 },
{ num: 9 },
{ num: 10 }
];
axios(url).then((res) => {
const newData = res.data.map((item, idx) => {
return { ...item, ...arrayOfObjects[idx] };
});
console.log(newData);
});
}, []);