Replace object1 values with values of object2 - javascript

var object1 = {
lol_gif: [22390036, 15154597, 13491369],
silly_gif: [19048808, 19048861]
}
var ids = Object.values(object1).toString();//will return 22390036,15154597,13491369,19048808,19048861
httpGetAsync('https://g.tenor.com/v1/gifs?ids=' + ids + '&key=LIVDSRZULELA&media_filter=tinygif');
function httpGetAsync(theUrl) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var response = JSON.parse(xmlHttp.responseText);
var gifs = response.results;
var object2 = {};
for (var g in gifs) {
var id = gifs[g].id;
object2[id] = gifs[g].media[0].tinygif.url;
}
console.log(object2);
//will return an object with the ID as the keys and gif url as the values
}
}
xmlHttp.open("GET", theUrl, true);
xmlHttp.send();
return;
}
I am trying to categorize each gif by replacing object1 values with data from tenor json but failed many times. thanks for your help!
desired output:
var object1 = {
lol_gif: ["https://media.tenor.com/images/4ad4bc701f2744ddc5220f6d3688e899/tenor.gif",
"https://media.tenor.com/images/c9b8564d6acbbba994b5413479d0fc2b/tenor.gif",
"https://media.tenor.com/images/7c27bea2fb5ea0f7600af7e9ad8d0c4a/tenor.gif"],
silly_gif: ["https://media.tenor.com/images/59669ec95913ef1df85fee2cda08aece/tenor.gif",
"https://media.tenor.com/images/59669ec95913ef1df85fee2cda08aece/tenor.gif"]
}

Something like this would give you an object in the same shape as your original:
var object1 = {
lol_gif: [22390036, 15154597, 13491369],
silly_gif: [19048808, 19048861]
}
var ids = Object.values(object1).toString();//will return 22390036,15154597,13491369,19048808,19048861
httpGetAsync('https://g.tenor.com/v1/gifs?ids=' + ids + '&key=LIVDSRZULELA&media_filter=tinygif');
function httpGetAsync(theUrl) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var response = JSON.parse(xmlHttp.responseText);
var gifs = response.results;
var object2 = {};
Object.entries(object1).forEach(([key, gifIds]) => {
const newGifList = gifIds.map((gifId) => {
const gif = gifs.find((gifResult) => gifResult.id === gifId.toString());
return gif.media[0].tinygif.url;
});
object2[key] = newGifList;
});
console.log(object2);
//will return an object with the ID as the keys and gif url as the values
}
}
xmlHttp.open("GET", theUrl, true);
xmlHttp.send();
return;
}
Side note, its generally not a great idea to include API keys in StackOverflow questions.

I haven't really taken a deep dive into the type of responses this API provides back, but my surface-level conclusion is that if you want to maintain the exact structure and order of the data, you'll have to go with this solution:
const object = {
lolGifs: [22390036, 15154597, 13491369],
sillyGifs: [19048808, 19048861],
};
const getGifs = async (obj) => {
const map = {};
for (const [key, arr] of Object.entries(obj)) {
map[key] = [];
for (const id of arr) {
const res = await fetch(`https://g.tenor.com/v1/gifs?ids=${id}&key=LIVDSRZULELA&media_filter=tinygif`);
const { results } = await res.json();
const gifUrl = results[0]?.media[0]?.tinygif?.url;
map[key].push(gifUrl);
}
}
return map;
};
(async () => {
const data = await getGifs(object);
console.log(data);
})();

You just need to make some simple change where you search for the ids to put it to the keyname as following:
var object1 = {
lol_gif: [22390036, 15154597, 13491369],
silly_gif: [19048808, 19048861]
}
var ids = Object.values(object1).toString();//will return 22390036,15154597,13491369,19048808,19048861
httpGetAsync('https://g.tenor.com/v1/gifs?ids=' + ids + '&key=LIVDSRZULELA&media_filter=tinygif');
function httpGetAsync(theUrl) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var response = JSON.parse(xmlHttp.responseText);
var gifs = response.results;
var object2 = {"lol_gif":[],"silly_gif":[]};
for (var g in gifs) {
var id = gifs[g].id;
if(object1["lol_gif"].indexOf(parseInt(id))!=-1) {
object2["lol_gif"].push(gifs[g].media[0].tinygif.url);
}
else if(object1["silly_gif"].indexOf(parseInt(id))!=-1){
object2["silly_gif"].push(gifs[g].media[0].tinygif.url);
}
}
console.log(object2);
//will return an object with the ID as the keys and gif url as the values
}
}
xmlHttp.open("GET", theUrl, true);
xmlHttp.send();
return;
}

Related

How can We access 2 dimensional array

enter image description here
How can i access a data.mac . I tried many times data[0].mac And did many try but I am not getting How can I access this .
Thank You
How to access a single value in 2 dimensional array.
const data = [];
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var res = this.responseText;
//console.log(res);
res.split(']').forEach((el) => {
if (!el) return;
const [mac, ttl, time] = el.split(',');
const obj = data.find(o => o.mac === mac);
if (obj) {
obj.ttl = ttl;
obj.time = time;
} else {
data.push({
mac,
ttl,
time
});
}
});
}
};
xhr.open("GET", "http://192.168.43.154/wifimac", true);
xhr.send();

How to split the content of xmlhttp.response in javascript

i did manage to build a code that works and it does the splitting when added manually:
var input = '10;11;15;16';
var arr = input.split(';');
// update the content of the div with ID "humid"
document.getElementById('humid').textContent = arr[0];
document.getElementById('humid').style.width = `${arr[0]}%`;
document.getElementById('temp').textContent = arr[1];
document.getElementById('temp').style.width = `${arr[1]}%`;
document.getElementById('uv').textContent = arr[2];
document.getElementById('uv').style.width = `${arr[2]}%`;
document.getElementById('info').textContent = arr[3];
document.getElementById('info').style.width = `${arr[3]}%`;
the problem i have is that i want to use the data from this XMLHttpRequest,
this is how i get my value:
function readForestall() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ForestAll").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "readFORESTALL", false);
xhttp.send();
}
setInterval(function() {
readForestall();
}, 5000);
i did try a lot of things with no result, like this:
var input = 'ForestAll';
or input = document.getElementById('ForestAll').value
regards

How to acces data from variable in begin function

Could someone help me out on this function structure what I try to do is seperate the functions like this:
function getNewResources (currentUrl, nextUrl)
{
let resourcesCurrentUrl = getResourceByUrl(currentUrl);
let resourcesNextUrl = getResourceByUrl(nextUrl);
// Diff resources
ACCESS DATA FROM ABOVE VARIABLES HERE!
// Return new resources
}
function getResourceByUrl (url)
{
let xmlhttp = new XMLHttpRequest();
let xmlResponse;
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4) {
// when succesfull
var resources = extractResourcesFromXMLResponse(this.response);
return resources;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function extractResourcesFromXMLResponse (xmlResponse)
{
let resources = [];
// Add images
imagePaths = extractImages(xmlResponse);
resources.push(imagePaths);
return resources;
}
function extractImages(xmlDoc)
{
let match,
extractedImages = [],
newArr = [],
rex = /<img.*?src="([^">]*\/([^">]*?))".*?>/g;
while ( match = rex.exec( xmlDoc ) ) {
extractedImages.push( match[1] );
}
return extractedImages;
}
How do I acces the returned resource variable in the getNewResource() function

AJAX does not return object

I am using AJAX GET to get a local JSON file and it does that, but once i try to return it says undefined.
ScoreHandler = function () {
this.getScores = function() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
//This logs object
console.log(data);
return data;
}
};
xmlhttp.open("GET", "JSON/Scores.json", true);
xmlhttp.send();
};
};
HighScores = function (scoreHandler) {
var scoreHandler = scoreHandler;
var scores = this.scoreHandler.getScores();
//This logs undefined
console.log(scores);
}
Just implement a callback for response, something like this
ScoreHandler = function () {
this.getScores = function(callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
//This logs object
console.log(data);
if(typeof callback === 'function')
callback(data);
//return data;
}
};
xmlhttp.open("GET", "JSON/Scores.json", true);
xmlhttp.send();
};
};
HighScores = function (scoreHandler) {
var scoreHandler = scoreHandler; //why this line use it directly
var scores = this.scoreHandler.getScores(function(data){
console.log("response", data); //you can see the data here
});
//This logs undefined
console.log(scores);
}

Downloading binary data using XMLHttpRequest, without overrideMimeType

I am trying to retrieve the data of an image in Javascript using XMLHttpRequest.
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.celticfc.net/images/doc/celticcrest.png");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
var resp = xhr.responseText;
console.log(resp.charCodeAt(0) & 0xff);
}
};
xhr.send();
The first byte of this data should be 0x89, however any high-value bytes return as 0xfffd (0xfffd & 0xff being 0xfd).
Questions such as this one offer solutions using the overrideMimeType() function, however this is not supported on the platform I am using (Qt/QML).
How can I download the data correctly?
Google I/O 2011: HTML5 Showcase for Web Developers: The Wow and the How
Fetch binary file: new hotness
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.celticfc.net/images/doc/celticcrest.png', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var uInt8Array = new Uint8Array(this.response); // Note:not xhr.responseText
for (var i = 0, len = uInt8Array.length; i < len; ++i) {
uInt8Array[i] = this.response[i];
}
var byte3 = uInt8Array[4]; // byte at offset 4
}
}
xhr.send();
I'm not familiarized with Qt but i found this in their documentation
string Qt::btoa ( data )
Binary to ASCII - this function returns a base64 encoding of data.
So, if your image is a png you can try:
resp = "data:image/png;base64," + btoa(resp);
document.write("<img src=\""+resp+"\">");
Qt version 5.13.1(support native Promise in qml env), prue qml.
function fetch, like node-fetch
function hexdump, dump the data as hex, just use the linux command hexdump to check.
function createResponse(xhr) {
let res = {};
function headersParser() {
let headersRaw = {};
let lowerCaseHeaders = {};
let rawHeaderArray = xhr.getAllResponseHeaders().split("\n");
for(let i in rawHeaderArray) {
let rawHeader = rawHeaderArray[i];
let headerItem = rawHeader.split(":");
let name = headerItem[0].trim();
let value = headerItem[1].trim();
let lowerName = name.toLowerCase();
headersRaw[name] = value;
lowerCaseHeaders [lowerName] = value;
}
return {
"headersRaw": headersRaw,
"lowerCaseHeaders": lowerCaseHeaders
};
}
res.headers = {
__alreayParse : false,
raw: function() {
if (!res.headers.__alreayParse) {
let {headersRaw, lowerCaseHeaders} = headersParser();
res.headers.__alreayParse = true;
res.headers.__headersRaw = headersRaw;
res.headers.__lowerCaseHeaders = lowerCaseHeaders;
}
return res.headers.__headersRaw;
},
get: function(headerName) {
if (!res.headers.__alreayParse) {
let {headersRaw, lowerCaseHeaders} = headersParser();
res.headers.__alreayParse = true;
res.headers.__headersRaw = headersRaw;
res.headers.__lowerCaseHeaders = lowerCaseHeaders;
}
return res.headers.__lowerCaseHeaders[headerName.toLowerCase()];
}
};
res.json = function() {
if(res.__json) {
return res.__json;
}
return res.__json = JSON.parse(xhr.responseText);
}
res.text = function() {
if (res.__text) {
return res.__text;
}
return res.__text = xhr.responseText;
}
res.arrayBuffer = function() {
if (res.__arrayBuffer) {
return res.__arrayBuffer;
}
return res.__arrayBuffer = new Uint8Array(xhr.response);
}
res.ok = (xhr.status >= 200 && xhr.status < 300);
res.status = xhr.status;
res.statusText = xhr.statusText;
return res;
}
function fetch(url, options) {
return new Promise(function(resolve, reject) {
let requestUrl = "";
let method = "";
let headers = {};
let body;
let timeout;
if (typeof url === 'string') {
requestUrl = url;
method = "GET";
if (options) {
requestUrl = options['url'];
method = options['method'];
headers = options['headers'];
body = options['body'];
timeout = options['timeout'];
}
} else {
let optionsObj = url;
requestUrl = optionsObj['url'];
method = optionsObj['method'];
headers = optionsObj['headers'];
body = optionsObj['body'];
timeout = optionsObj['timeout'];
}
let xhr = new XMLHttpRequest;
if (timeout) {
xhr.timeout = timeout;
}
// must set responseType to arraybuffer, then the xhr.response type will be ArrayBuffer
// but responseType not effect the responseText
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function() {
// readyState as follow: UNSENT, OPENED, HEADERS_RECEIVED, LOADING, DONE
if(xhr.readyState === XMLHttpRequest.DONE) {
resolve(createResponse(xhr));
}
};
xhr.open(method, requestUrl);
// todo check headers
for(var iter in headers) {
xhr.setRequestHeader(iter, headers[iter]);
}
if("GET" === method || "HEAD" === method) {
xhr.send();
} else {
xhr.send(body);
}
});
}
function hexdump(uint8array) {
let count = 0;
let line = "";
let lineCount = 0;
let content = "";
for(let i=0; i<uint8array.byteLength; i++) {
let c = uint8array[i];
let hex = c.toString(16).padStart (2, "0");
line += hex + " ";
count++;
if (count === 16) {
let lineCountHex = (lineCount).toString (16).padStart (7, "0") + "0";
content += lineCountHex + " " + line + "\n";
line = "";
count = 0;
lineCount++;
}
}
if(line) {
let lineCountHex = (lineCount).toString (16).padStart (7, "0") + "0";
content += lineCountHex + " " + line + "\n";
line = "";
// count = 0;
lineCount++;
}
content+= (lineCount).toString (16).padStart (7, "0") + count.toString(16) +"\n";
return content;
}
fetch("https://avatars2.githubusercontent.com/u/6630355")
.then((res)=>{
try {
let headers = res.headers.raw();
console.info(`headers:`, JSON.stringify(headers));
let uint8array = res.arrayBuffer();
let hex = hexdump(uint8array);
console.info(hex)
}catch(error) {
console.trace(error);
}
})
.catch((error)=>{
});

Categories

Resources