0

I am getting two results, one which is in form of json and the other just as text from different sources. I need to append the results together, I have tried some methods but seems I am not getting it right.

Here is my first code and the json result attached below

const posts = fetch('https://jsonplaceholder.typicode.com/posts')
  .then(response => response.json())
  .then(json => console.log(json.slice(0, 2)))

Here is the json result

[
  {
    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'
  }
]

Here is the second code and the json result attached below

function generateNames(){
  for (let i = 0; i < 2; i++) {
    const playersName = fetch('https://www.balldontlie.io/api/v1/players?per_page=5')
      .then(response => response.json())
      .then(json => console.log(json['data'][i]['first_name']))
  }
} 
generateNames()

Here is the result

Ike
Ron

What I am trying to achieve is something of this format

[
  {
    first_name: 'Ike',
    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: 'Ron',
    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'
  }
]
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
oyerohabib
  • 187
  • 3
  • 16

2 Answers2

1

You will need to ensure that the data are combined once both sets of data have been fetched. Drawing on this answer you can do that like this:

const fetchJson = url => fetch(url).then(r => r.json());
const [allPosts, allNames] = await Promise.all([fetchJson("https://jsonplaceholder.typicode.com/posts"), fetchJson("https://www.balldontlie.io/api/v1/players?per_page=5")]);
const combined = allPosts.slice(0, 2).map((post, index) => ({firstName: allNames.data[index].first_name, ...post}))
Stuart
  • 9,597
  • 1
  • 21
  • 30
1

try this

function AddNames(json1) {
  var json2 = ["Ike", "Ron"];
  var i = 0;
  json1.forEach((element) => {
    element.first_name = json2[i];
    if ((i == 1)) return;
    i++;
  });
}

var posts = fetch("https://jsonplaceholder.typicode.com/posts")
  .then((response) => {
    return response.json();
  })
  .then((json) => {
    AddNames(json.slice(0, 2));
  });

or you can use this syntax

async function getPosts(num) {
  let posts = await fetch('https://jsonplaceholder.typicode.com/posts')
  .then(response => response.json())
  .then(json => {
    return json.slice(0,num);
   })
  return posts;
}

async function AddNames() {
  var json1= await getPosts(2);
  var json2 = ["Ike", "Ron"];
  var i = 0;
   json1.forEach((element) => {
     element.first_name = json2[i];
     if ((i == 1)) return;
     i++;
   });
   console.log(json1);
}

AddNames();
Serge
  • 40,935
  • 4
  • 18
  • 45