Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

502
Vistas
How can I concatenate two JSON files to produce a single JSON result?

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'
  }
]
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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}))
about 4 years ago · Juan Pablo Isaza Denunciar

0

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();
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda