TransWikia.com

is there any way to give name object?

Stack Overflow Asked by Beginner Coder on December 14, 2020

I have fetch API request like this

fetch('http://127.0.0.1:8000/api/usersRecords')
    .then(response=>response.json())
    .then(data=>{
       console.log(data.usersRecords);
  });

When I do console.log(data.usersRecords)

(3) [{…}, {…}, {…}]
 0: {"id": 1, "name": "Robbie", "kill": 12 , "knock": 1}
 1:  {"id": 2, "name": "Mohamand", "kill": 12 , "knock": 4}
 2:  {"id": 3, "name": "Jebisha", "kill": 8 , "knock": 4}
 length: 3
 __proto__: Array(0)

I have two URL needed to be fetch

 fetch('http://127.0.0.1:8000/api/usersRecords')
        .then(response=>response.json())
        .then(data=>{
           console.log(data.usersRecords);
      });
 fetch('http://127.0.0.1:8000/api/usersRecord1')
        .then(response=>response.json())
        .then(data=>{
           console.log(data.usersRecords1);
      });

I want to make an array like this from above fetch and use them to merge two API requests and sum their data of kill and knock only

var demo = {
     "key1": [{"id": 1, "name": "Robbie", "kill": 12 , "knock": 1}, 
               {"id": 2, "name": "Mohamand", "kill": 12 , "knock": 4},
               {"id": 3, "name": "Jebisha", "kill": 8 , "knock": 4}],

    "key2": [
             {"id": 1, "name": "Robbie", "kill":12  , "knock": 4}, 
             {"id": 2, "name": "Mohamand", "kill": 13 , "knock": 3},
             {"id":3, "name": "Jebisha", "kill": 5 , "knock": 1}]
 };
Further, I need to merge two URLs and sum their data kill and knock. So this is code to merge and sum their kill and knock.

    var res = demo.key1.map(function(item, idx) {
    return Object.keys(item).reduce(function(obj, key) {
        if (key == 'name') {
            obj[key] = item[key];
        } else {
            obj[key] = item[key] + demo.key2[idx][key];
        }

        return obj;
    }, {});
});

One Answer

fetch('http://127.0.0.1:8000/api/usersRecords')
    .then(response=>response.json())
    .then(data=>{
       let myObject = {"key1" : data.usersRecords};
       console.log(myObject);
  });

Answered by Nate G on December 14, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP