How can I get the first pair of key value from ajax returned json?
Like in console, if I input response[0] to get testdaa101.com ?
.ajax({
url: "/fetch_bar",
type: "post",
dataType: "json",
async: true,
success: function(response) {#
response = {
testdaa101.com: "30",
testbb101.com: "50"
}
var len = Object.keys(response).length;
var selects = document.querySelectorAll("select[id=select_host]");
if (len == 1) {
for (var index = 0; index < selects.length; index++)
if (selects[index].value == response[0])
alert("hello")
else if (len > 1) {
for (var ind = 0; ind < len; ind++) {
for (var index = 0; index < selects.length; index++)
if (selects[index].value == response[ind]) {
alert("nice")
}
// if (response[0]){ alert
You can use Object.keys to get keys, and then take the first:
const fakeAjax = () => new Promise((res) => {
setTimeout(() => res({
first: 1,
second: 2
}))
})
fakeAjax().then(data => {
console.dir(Object.keys(data)[0]);
})
function getFirstPair(response) {
var keyValuePairs = Object.entries(response);
if (keyValuePairs.length) return { [keyValuePairs[0][0]]: keyValuePairs[0][1] };
return {};
}
getFirstPair({
"testdaa101.com": "30",
"testbb101.com": "50"
})
This would return {testdaa101.com: "30"}. But the order of key value pairs in a JSON object is not consistent. So be cautious on that point
Related
url:'{{ route("dashboard.diklat_name") }}',
data:{dari:dari, sampai:sampai},
type: 'get',
dataType: 'json',
success:function(response) {
var len = 0;
len = response['data'].length;
if (len > 0) {
for (var index = 0; index < len; index++) {
document.getElementById('diklat_name').innerHTML = response['data'][index].name;
console.log(response['data'][index].name);
}
}
}
this code give me 1 display. but in log it's return as many data that i get.
for example i have 50 data and i want to display it in
thanks
Try this.
url:'{{ route("dashboard.diklat_name") }}',
data:{dari:dari, sampai:sampai},
type: 'get',
dataType: 'json',
success:function(response) {
var len = 0;
len = response['data'].length;
if (len > 0) {
let data = '';
response['data'].forEach((item) => {
data += "<p>" + item.name + "</p>";
console.log(item.name);
)}
document.getElementById('diklat_name').innerHTML = data;
}
}
You can get all the data inside p tag using string interpolation and concating all the resulting p tags.
let allNamesElement = '';
for (var index = 0; index < len; index++) {
allNamesElement += `<p>${response['data'][index].name}</p>`;
console.log(response['data'][index].name);
}
document.getElementById('diklat_name').innerHTML = allNamesElement;
You can try this
url:'{{ route("dashboard.diklat_name") }}',
data:{dari:dari, sampai:sampai},
type: 'get',
dataType: 'json',
success:function(response) {
var len = 0;
len = response['data'].length;
let html = document.getElementById('diklat_name').innerHTML;
if (len > 0) {
for (var index = 0; index < len; index++) {
html += response['data'][index].name;
console.log(response['data'][index].name);
}
}
}
I'm currently developing a Chrome extension that is supposed to scrape my Internet activity. So first of all here is my JS code (I only have this file without counting the manifest.json, the jquery.js and the logo) :
function getAllIndexes(arr, val) {
var indexes = [], i = -1;
while ((i = arr.indexOf(val, i+1)) != -1){
indexes.push(i);
}
return indexes
}
chrome.tabs.onUpdated.addListener(function (tabId, info) {
if(info.status === 'complete') {
chrome.tabs.executeScript({
code: "document.documentElement.outerHTML"
}, function(result) {
if (!chrome.runtime.lastError) {
var el = document.createElement( 'html' );
el.innerHTML = result[0];
var scraping = [
{
"url": "",
"title": "",
"text": "",
"ranking_word": {},
"a": [],
"img": [],
"html": ""
}
]
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
scraping[0]["url"]= tabs[0].url;
});
var head = el.getElementsByTagName('head');
for (var i = 0; i < head.length; i++) {
scraping[0]["title"] = head[i].getElementsByTagName('title')[0].innerHTML;
}
var a = el.getElementsByTagName('a');
for (var i = 0; i < a.length; i++) {
scraping[0]["a"].push(a[i].href);
}
var img = el.getElementsByTagName('img');
for (var i = 0; i < img.length; i++) {
scraping[0]["img"].push(img[i].src);
}
var txt = "";
var text_in_body = [];
var body = el.getElementsByTagName('body');
for (var i = 0; i < body.length; i++){txt += body[i].textContent;}
txt = txt.split("\n");
for (var i = 0; i < txt.length; i++){txt[i] = txt[i].split(" ")}
for (var i = 0; i < txt.length; i++) {for (var a = 0; a < txt.length; a++){if (txt[i][a] == " " || txt[i][a] == "" || txt[i][a] == "," || txt[i][a] == "." || txt[i][a] == "!" || txt[i][a] == "?" || txt[i][a] == ";"){delete txt[i][a];}}}
for (var i = 0; i < txt.length; i++) {text_in_body = text_in_body.concat(txt[i])}
scraping[0]["text"] = text_in_body.join(" ");
ranking_word = {}
for (var i = 0; i < text_in_body.length; i++) {
ranking_word[text_in_body[i]] = getAllIndexes(text_in_body, text_in_body[i]).length;
}
scraping[0]["ranking_word"] = ranking_word;
scraping[0]["html"] = result;
var response = $.get("https://api.myjson.com/bins/1e0ybo", function(data, textStatus, jqXHR) {
if (textStatus == "success") {
console.log("%cSuccess: Getting Data", 'background-color: #8cc2e6; color: #000');
console.log(response.responseJSON);
console.log(scraping);
var newJSON = Object.assign(response.responseJSON, scraping);
console.log(newJSON)
$.ajax({
url:"https://api.myjson.com/bins/1e0ybo",
type:"PUT",
data:JSON.stringify(newJSON),
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(data, textStatus, jqXHR){
console.log("%cSuccess: Uploading Data", 'background-color: #8cc2e6; color: #000')
}
});
}
});
}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
On lines 72, 73 and 75 I put console.log() to check that all variables had the values they should have, except that it's not the case (as you can see on the console screenshot below) .
I don't understand why my response.responseJSON value (I also tried with data but it gave me the same thing) and my scraping variable are equal, they shouldn't be. I checked that my file where I get the data didn't have those values but no...
Anyone have any idea how to fix this?
The screenshot
$('#createFields').click(function () {
for (var i = 0; i <= numberOfFields; i++) {
fieldsArray[i] = {};
console.log(fieldsArray);
};
});
i get the numberOfFields variable from a select box
$("body").on("change","input:checkbox",
function () {
if ($(this).prop('checked')) {
var val = $(this).prop('value');
addColumns(val);
}
else {
console.log("deleting...")
singleArray=singleArray.splice(singleArray.length, newArray.length);
InitData();
}
}
);
I call the addColumns function each time a checkbox is checked.
function addColumns(val) {
var defer = $.Deferred();
newArray = [];
str = [];
str.push(val);
var url = ListJoin.appweburl + "/_api/SP.AppContextSite(#target)/Web/Lists/getbytitle('" + selectedList + "')/items?$select=" + str + "" +
"&#target='" + ListJoin.hostweburl + "'";
ListJoin.executor.executeAsync({
url: url,
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function (data) {
var jsonObject = JSON.parse(data.body);
var response = jsonObject.d.results;
for (var i = 0, len = response.length; i < len; i++) {
var tu = [];
var keys = Object.keys(response[i]);
//Skip keys[0] because it's always metadata
for (var j = 1; j < keys.length; j++) {
var key = keys[j];
var val = [response[i][key]];
console.log("bujar" + val);
newArray.push(val);
}
}
fieldsArray[1].push(newArray);
can not push neither concat newArray=['BBB','MMM','CCC'] to the an array of the fieldsArray array
InitData();
defer.resolve();
},
error: function (data) {
console.log(data);
defer.reject();
}
});
return defer;
}
In the code below, I assign a value to a variable from JSON with this var tag = data[j]['text']; and I output it with this console.log(tag); (for testing) which works.
I try to push the values into an array with tags.push(tag); but it WILL NOT WORK!
Why won't these values go into the array? I am just trying to get the contents of tag into an array...
function GetAvailableTags() {
var url = '/TextCodes/TextCodes?key=';
var tagGroups = [];
$('.ui-autocomplete-input').each(function () {
var key = $(this).attr('id');
var tags = [];
//console.log(key);
$.getJSON(url + key, function (data) {
for (var j = 0, len = data.length; j < len; j++) {
var tag = data[j]['text'];
console.log(tag);
tags.push(tag);
}
});
console.log(tags.length);
for (var k = 0, len = tags.length; k < len; k++) {
console.log(tags[k]);
}
});
}
Thanks for your help.
Because $.getJSON is an asynchronous function. It means that your code
console.log(tags.length);
for (var k = 0, len = tags.length; k < len; k++) {
console.log(tags[k]);
}
will be executed before the $.getJSON callback function :
function () {
var key = $(this).attr('id');
var tags = [];
//console.log(key);
$.getJSON(url + key, function (data) {
for (var j = 0, len = data.length; j < len; j++) {
var tag = data[j]['text'];
console.log(tag);
tags.push(tag);
}
}
It is why your variable seems to be empty when look into in your code above, but how it is possible that the data are printed with console.log(tag); in the callback function.
Update
Here is an example of using $.ajax method instead of $.getJSON to specify that the data must be retrieved synchronously using the parameter asynch : false
By that way, the server call response (success callback) is mandatory to continue the process. The disadvantage of this non-standard way is that your web page could be freezed waiting the server response. It is not the best elegant way to do that, but sometimes it is useful.
function GetAvailableTags() {
var url = '/TextCodes/TextCodes?key=';
var tagGroups = [];
$('.ui-autocomplete-input').each(function () {
var key = $(this).attr('id');
var tags = [];
//console.log(key);
$.ajax({
url: url + key,
type: 'POST',
asynch: false,//specify to stop JS execution waiting the server response
success: function (data) {
for (var j = 0, len = data.length; j < len; j++) {
var tag = data[j]['text'];
console.log(tag);
tags.push(tag);
}
},
error : function(jqXHR, textStatus, errorThrown) {
alert('an error occurred!');
}
});
console.log(tags.length);
for (var k = 0, len = tags.length; k < len; k++) {
console.log(tags[k]);
}
});
}
My solution is kind of long and stupid, but it works. Now, I can access the variables like an array textCodes['taxes']. sdespont's async note helped, too.
var textCodes = GenerateTextCodes();
console.log(textCodes);
function GenerateTextCodes() {
var arr = [];
$('.ui-autocomplete-input').each(function () {
var id = $(this).attr('id');
arr[id] = GetAvailableTags(id);
});
//console.log(arr['taxes']);
return arr;
}
// get all autocomplete element IDs and put them into an array
function GetAvailableTags(key) {
var url = '/TextCodes/TextCodes?key=';
var tags = [];
$.ajax({
url: url + key,
type: 'GET',
async: false,
success: function (data) {
//console.log(data[0].text);
//console.log(data.length);
for (var i = 0; i < data.length; i++) {
//console.log(data[i].text);
tags.push(data[i].text);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('an error occurred!');
}
});
//console.log(tags);
return tags;
}
I've json like this. in that json there is object name tipe and I want to sum act_qty1, act_val1, acvqty, acvval, budqty, budval, cm_val1, cm_val2, cm_val3 in the same tipe(e.g. sum them where their tipe is "ESL"). How to sum that in javascript? can it done with loop?
here is what I've made so far:
function detail(kodenegara, koderesult)
{
$.mobile.showPageLoadingMsg();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://www.greenfields.co.id:502/Service1.svc/"+kodenegara,
dataType: "json",
success:function(data){
var result = koderesult;
var details = "";
for (i = 0; i < data[result].length; i++){
$("#"+data[result][i].tipe).empty();
}
for (i = 0, types={} ; i < data[result].length; i++){
$("#"+data[result][i].tipe).append("<tr>"+
"<td>"+data[result][i].mc+"</td>"+
"<td>"+data[result][i].value3+"</td>"+
"<td>"+data[result][i].value2+"</td>"+
"<td>"+data[result][i].value1+"</td>"+
"<td>"+data[result][i].avgqty+"</td>"+
"<td>"+data[result][i].budqty+"</td>"+
"<td>"+data[result][i].budval+"</td>"+
"<td>"+data[result][i].acvqty+"</td>"+
"<td>"+data[result][i].acvval+"</td>"+
"</tr>").trigger('create');
//----------------------------------//
// HERE IS what I've made TO SUM THE VALUES //
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv//
for(i = 0; i < data[result].length; i++) {
if(data[result][i].tipe == 'ESL')
{
//how to summing data[result][i].cm_val3 where data[result][i].tipe == 'ESL'
var b = i + 1;
var test = parseInt(data[result][i].cm_val3) + parseInt(data[result][b].cm_val3)
}
}
}
//show the page
$.mobile.changePage("#detail_"+kodenegara, "slide", false, true);
},
error: function () {
alert("ERROR");
}
});
}
I don't know how to write the right looping for summing the value while tipe is "ESL" (or "ESL1L" or "WHP" or else). if I use this:
var b = i + 1;
var test = parseInt(data[result][i].cm_val3) + parseInt(data[result][b].cm_val3)
that only sum the last array. how to write the right looping to sum with that condition?
Here come a working fiddle
http://jsfiddle.net/xKJn8/1/
var SumByTipe = {};
for(i in data.GetReportIdResult){
var currtipe = data.GetReportIdResult[i].tipe;
if (currtipe){
if (currtipe in SumByTipe){
for (j in data.GetReportIdResult[i]){
if (j != "tipe" && j != "mc"){
SumByTipe[currtipe][j + '_total'] += parseFloat(data.GetReportIdResult[i][j]);
}
}
}else{
var firstSum = {};
for (j in data.GetReportIdResult[i]){
if (j != "tipe" && j != "mc"){
firstSum[j + '_total'] = parseFloat(data.GetReportIdResult[i][j]);
}
}
SumByTipe[currtipe]=firstSum;
}
}
}
console.debug(SumByTipe);
That should do the trick :
var sum_cm_val3=0;
for (var i=0;i<data[result].length;i++) {
if (data[result][i].tipe == "ESL") {
var cm_val3 = data[result][i].cm_val3;
if (parseInt(cm_val3)==cm_val3) {
sum_cm_val3 += parseInt(cm_val3);
}
}
}