简体   繁体   中英

How can I concatenate two equally structured JSON datasets in JavaScript?

I have the following code which calls two different API's, parses the JSON data and displays it on a webpage. Both JSON datasets have the same structure, one with 5 columns and the other one with 20 columns.

The JavaScript code I am using is shown below. How can I combine both JSON datasets into one, so there's a resulting dataset with 25 columns, enabling me to search/reference across all those 25 columns?

The Data Structure of both JSON datasets is as follows:

 { "datatable": { "data": [ [ "TSLA", "2019-02-22", "2019-02-22", 58995.9, -231.2 ] ], "columns": [ { "name": "ticker", "type": "String" }, { "name": "date", "type": "Date" }, { "name": "lastupdated", "type": "Date" }, { "name": "ev", "type": "BigDecimal(15,3)" }, { "name": "evebit", "type": "BigDecimal(15,3)" } ] }, "meta": { "next_cursor_id": null } } 

The JavaScript Code is as follows:

 var apiurls = [ 'api1.json', 'api2.json' ], elroot = document.getElementById('root'), index = 0; function setup() { loadJSON(apiurls[index], gotData); } function gotData(data) { var daten = data.datatable.data[0], spalten = data.datatable.columns, output = ''; for (var i = 0; i < spalten.length; i++) { output = '<p>' + spalten[i].name + ': ' + daten[i] + '</p>'; elroot.innerHTML += output; } if (++index < apiurls.length) { setup(); } } 

something like that ?

 var Json_1 = { "datatable": { "data" : ['aa','bb','cc'], "columns": ['x','y','z'] }, "meta": { 'meta1': 15, 'meta2':87 } }, Json_2 = { "datatable": { "data" : ['ZZbb','cZc'], "columns": ['xf','yf','zf','zgg'] }, "meta": { 'meta1': 879, 'meta2':4 } }, Json_cumul_typ0 = { Json_1, Json_2 }, Json_cumul_typ1 = { "data" : [].concat( Json_1.datatable.data, Json_2.datatable.data ), "columns": [].concat( Json_1.datatable.columns, Json_2.datatable.columns ), } ; console.log( Json_cumul_typ0 ); console.log( Json_cumul_typ1 ); 

It would be easier to make all the API calls first, combining them into a single result object before doing any processing. Currently, you are making an API call, then processing the results before making the next API call.

I think the nature of async callbacks is making your task more difficult. I suggest using async/await to simplify the logic. Something like this:

var apiurls = [
    'api1.json',
    'api2.json'
  ],
  elroot = document.getElementById('root');

// Combine all API responses into this object
allResults = {
  data: [[]],
  columns: []
};


// loadJSON() is probably not async, so here is an async version using fetch()
async function loadJSON(url) {
  response = await fetch(url);
  return response.json()
}

// Wrap logic in async function so await can be used
(async () => {
    // First make all the API calls
    for (url of apiurls) {
        results = await loadJSON(url);
        allResults.data[0] = allResults.data[0].concat(results.datatable.data[0]);
        allResults.columns = allResults.columns.concat(results.datatable.columns);
    }

    // Then process combined allResults object here once.
    var daten = allResults.data[0],
        spalten = allResults.columns,
        output = '';

    for (var i = 0; i < spalten.length; i++) {
        output = '<p>' + spalten[i].name + ': ' + daten[i] + '</p>';
        elroot.innerHTML += output;
    }
})();

The loadJSON() you are using probably isn't async. Here are some alternatives you can use:

var object1 = {
    "datatable": {
        "data": [],
        "columns": [1,2,3,4]
    },
    "meta": {}
}
var object2 = {
    "datatable": {
        "data": [],
        "columns": [6,7,8,9,0,11,12,123]
    },
    "meta": {}
}

Now you want to concatenate columns field. So what you can do is create a deep copy of one of the above. There are better ways to do this than the one mentioned below.

var object3 = JSON.parse(JSON.stringify(object1));

Now to concatenate columns do this,

object3.datatable.columns = object3.datatable.columns.concatenate(object2.datatable.columns);

If you want to concatenate multiple fields you can use a for loop on an object, check if the data type is an array and do the concatenation.

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM