I am getting a weird kind of issue. I have a function getPosts which return a json object, when I run a .map() function on it, I get error TypeError: getPosts(...).forEach is not a function
, but when I store the value of getPosts in a variable, such as json1 and then run the .map()
function on it, it works perfectly. I don't know why that is happening.
async function getPosts() {
let posts = await fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(json => {
return json.slice(0, 5)
})
}
var json2=["Ike","Ron"];
var i=0;
getPosts().forEach(element => {
element.first_name=json2[i]; i++;
});
console.log(getPosts())
Error Log
TypeError: getPosts(...).forEach is not a function
result of getPosts stored in var json1 is
let json1 = [
{
userId: 1,
id: 1,
title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
body: 'quia et suscipit\n' +
'suscipit recusandae consequuntur expedita et cum\n' +
'reprehenderit molestiae ut ut quas totam\n' +
'nostrum rerum est autem sunt rem eveniet architecto'
},
{
userId: 1,
id: 2,
title: 'qui est esse',
body: 'est rerum tempore vitae\n' +
'sequi sint nihil reprehenderit dolor beatae ea dolores neque\n' +
'fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\n' +
'qui aperiam non debitis possimus qui neque nisi nulla'
}
]
when I run the .map() function here, it works fine and I get the expected result
var json2=["Ike","Ron"];
var i=0;
json1.forEach(element => {
element.first_name=json2[i]; i++;
});
console.log(json1)
expected result is as below and works fine
[
{
userId: 1,
id: 1,
title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
body: 'quia et suscipit\n' +
'suscipit recusandae consequuntur expedita et cum\n' +
'reprehenderit molestiae ut ut quas totam\n' +
'nostrum rerum est autem sunt rem eveniet architecto',
first_name: 'Ike'
},
{
userId: 1,
id: 2,
title: 'qui est esse',
body: 'est rerum tempore vitae\n' +
'sequi sint nihil reprehenderit dolor beatae ea dolores neque\n' +
'fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\n' +
'qui aperiam non debitis possimus qui neque nisi nulla',
first_name: 'Ron'
}
]
updated code after returning the posts
async function getPosts() {
let posts = await fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(json => json.slice(0, 5))
return posts
}
getPosts()