Darian Steyn Darian Steyn -4 years ago 62
HTML Question

How to split a JSON object in two and append each seperately

I am using JSON and Ajax to bring in data. I have a rates object with various exchange rates.

All I want to do is split the object in half and then append each half separately to a div. I can't seem to figure out how to split a JSON object.

I have attached a snippet of my code and marked the problem area with a PROBLEM AREA commment. I have also included a link to the JSON data file.

CODE -



var str = $.getJSON('http://api.fixer.io/latest?base=ZAR', {
action: "query"
, list: "search"
, format: "json"
, },

function (data) {
var baseCurr = data.base;
var baseDate = data.date;

$('#curr-cont').append('<div class="base row1" id="row1"><div class="base flag" id="flag"><i class="famfamfam-flag-za"></i></div><div class="base country-name"><p class="c-name" id="count-name">' + baseCurr + '</p></div><div class="base currency"><p class="c-amount" id="curr">' + baseDate + '</p></div></div>');

$.each(data.rates, function (i, item) {
var amount = [item];
var name = [i];
var maxLength = 4;
var string = amount.toString();
string = string.substr(0, maxLength);
// amount = amount.substr(0, maxLength);
$('#curr-cont').append('<div class="row1" id="row1"><div class="flag" id="flag"><i class="famfamfam-flag-' + name + '"></i></div><div class="country-name"><p class="c-name" id="count-name">' + name + '</p></div><div class="currency"><p class="c-amount" id="curr">' + string + '</p></div></div>');

//***Problem Area** I am trying to count the objects in the array and then halve it, this is probably wrong approach

var count = Math.ceil(Object.keys(data.rates).length/2);
console.log(count);
});


});





JSON data file

Answer Source

You were pretty much on the right track - although having this logic inside an each of all the data.rates seems a bit weird. Below is the logic to split an associative array into 2 parts getting the keys & values

var data = {"base":"ZAR","date":"2017-03-22","rates":{"AUD":0.10349,"BGN":0.14369,"BRL":0.24601,"CAD":0.10622,"CHF":0.078716,"CNY":0.54686,"CZK":1.9852,"DKK":0.54641,"GBP":0.063765,"HKD":0.61677,"HRK":0.54432,"HUF":22.714,"IDR":1058.3,"ILS":0.29021,"INR":5.1943,"JPY":8.8215,"KRW":88.906,"MXN":1.5201,"MYR":0.35154,"NOK":0.67198,"NZD":0.1128,"PHP":3.9874,"PLN":0.31457,"RON":0.33495,"RUB":4.603,"SEK":0.69874,"SGD":0.111,"THB":2.7496,"TRY":0.28768,"USD":0.079399,"EUR":0.07347}}

var keys = Object.keys(data.rates);
var half = Math.ceil(keys.length/2);
for(var i = 0;i<half;i++)
    console.log("First half", keys[i], data.rates[keys[i]]);
    
for(var i =half;i<keys.length;i++)
    console.log("Second half", keys[i], data.rates[keys[i]]);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download