Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

497
Views
¿Cómo puedo concatenar dos archivos JSON para producir un único resultado JSON?

Obtengo dos resultados, uno en forma de json y el otro como texto de diferentes fuentes. Necesito agregar los resultados juntos, probé algunos métodos pero parece que no lo estoy haciendo bien.

Aquí está mi primer código y el resultado json adjunto a continuación

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

Aquí está el resultado json

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

Aquí está el segundo código y el resultado json adjunto a continuación

 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()

aquí está el resultado

 Ike Ron

Lo que estoy tratando de lograr es algo de este formato.

 [ { 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 answers
Answer question

0

Deberá asegurarse de que los datos se combinen una vez que se hayan obtenido ambos conjuntos de datos. Basándose en esta respuesta , puede hacerlo así:

 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 Report

0

prueba esto

 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)); });

o puedes usar esta sintaxis

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!