How can We access 2 dimensional array - javascript

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();

Related

Replace object1 values with values of object2

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;
}

How do I get certain a property value from multiple objects using json?

I'm using this site:
https://jsonplaceholder.typicode.com/users/
as ajax practice with javascript.
I'm trying to get a certain property value from multiple IDs.
Let's use phone for example.
How can I loop through all the files and get every id and his phone?
Like this:
id : 1
phone : 123
id : 2
phone : 124
I'm trying to use for...in but I can't really get the hang of it rather than looping through only 1 of them.
function callToServer(param) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
//if (this.readyState == (4) Done && this.status == (200) All good) {
if (this.readyState == 4 && this.status == 200) {
res = JSON.parse(this.responseText);
for (var key in res) {
demo.innerHTML += `${key} : ${res[key]}<br>`;
}
}
}
// notice that I used "9" after to loop only through 1 :)
xhttp.open("GET", "https://jsonplaceholder.typicode.com/users/9", true);
xhttp.send();
}
Loop over the array and get the id and phone properties of each element. You can use forEach() for this rather than a for loop. See Why is using "for...in" for array iteration a bad idea?
function callToServer() {
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let html = '';
let res = JSON.parse(this.responseText);
res.forEach(user => demo.innerHTML +=
html += `id ${user.id}: phone ${user.phone}<br>`;
)
demo.innerHTML = html;
}
}
xhttp.open("GET", "https://jsonplaceholder.typicode.com/users", true);
xhttp.send();
}
Access your data using res[key].id
function callToServer(param) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
res = JSON.parse(this.responseText);
for (var key in res) {
demo.innerHTML += `${key} : ${res[key].id}<br>`;
}
}
}

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 concat two called endpoints to one string and print it in console

My function has to call two endpoints and concat them in one string at the same time. My code is simply a function that is getting two endpoints at the same time and print it in console.
But the same function has to concat them to one string.
I tried to create separated variables contains each call and then simply concat them, but the result hadn't been any different.
I read about it for couple of hours, and I see no, even the smallest tip anywhere.
EDIT: Please mind that each endpoint is an actual array.
function endpointsToOneString() {
const Http = new XMLHttpRequest();
const url = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
Http.open("GET", url);
Http.send();
Http.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(Http.responseText)
}
}
const HttpTwo = new XMLHttpRequest();
const urlTwo = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
HttpTwo.open("GET", urlTwo);
HttpTwo.send();
HttpTwo.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(Http.responseText)
}
}
}
endpointsToOneString();
In this case you should use Promise feature of javascript.
Here you can learn how to promisify your native XHR. Morever, Here you can find about promise chaining.
I have just added Promise in your code but it needs to be refactored.
Update: From comment, you want your response texts as a plain string. But we are actually getting a JSON array as response. So, we need to parse it using JSON.parse() function to make it an array object. Then we need to use .join() method to join all element of the array into a string. See the code below:
function endpointsToOneString() {
var requestOne = new Promise(function(resolve, reject){
const Http = new XMLHttpRequest();
const url = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
Http.open("GET", url);
Http.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(Http.response);
} else {
reject({
status: this.status,
statusText: Http.statusText
});
}
};
Http.onerror = function () {
reject({
status: this.status,
statusText: Http.statusText
});
};
Http.send();
});
var requestTwo = new Promise(function(resolve, reject){
const HttpTwo = new XMLHttpRequest();
const urlTwo = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
HttpTwo.open("GET", urlTwo);
HttpTwo.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(HttpTwo.response);
} else {
reject({
status: this.status,
statusText: HttpTwo.statusText
});
}
};
HttpTwo.onerror = function () {
reject({
status: this.status,
statusText: HttpTwo.statusText
});
};
HttpTwo.send();
});
Promise.all([
requestOne,
requestTwo
]).then(function(result){
var response = JSON.parse(result[0]).join();
response += JSON.parse(result[1]).join();
console.log(response);
});
}
endpointsToOneString();
I understand you want to concat the result of two parallel requests. In that case you can use a library like axios. From their docs
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// Both requests are now complete
}));
So for your example:
function getEndpoint1() {
return axios.get('https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json');
}
function getEndpoint2() {
return axios.get('https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json');
}
axios.all([getEndpoint1(), getEndpont2()])
.then(axios.spread(function (resp1, resp2) {
// Both requests are now complete
console.log(resp1 + resp2)
}));
try to have a look on the Promise.all method:
https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
As in this answer you should wrap your XHR in a Promise and then handle resolving of all function call. In this way you can access endpoint results in order.
Here's a working fiddle:
function makeRequest(method, url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function() {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function() {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send();
});
}
let url1 = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
let url2 = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json'
Promise.all([makeRequest('GET', url1), makeRequest('GET', url2)])
.then(values => {
debugger;
console.log(values);
});
https://jsfiddle.net/lbrutti/octys8k2/6/
Is it obligatory for you to use XMLHttpRequest? If not, u had better use fetch, because it returns Promise and with Promise it would be much simpler.
Rather than immediately printing them, save them to local variables, then print them at the end:
function endpointsToOneString() {
let response; // this line here declares the local variable
results = 0; // counts results, successful or not
const Http = new XMLHttpRequest();
const url = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
Http.open("GET", url);
Http.send();
Http.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
response = Http.responseText; //save one string
}
if (this.readyState == 4) {
results++;
}
}
const HttpTwo = new XMLHttpRequest();
const urlTwo = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
HttpTwo.open("GET", urlTwo);
HttpTwo.send();
HttpTwo.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
response += HttpTwo.responseText // save the other string
}
if (this.readyState == 4) {
results++;
}
}
while(results < 2) {} //loops until both requests finish, successful or not
console.log(response); //print total string
}
endpointsToOneString();
Also, HttpTwo's onreadystatechange function is calling for Http.responseText, rather than HttpTwo.responseText. Fix that as well for best results.
EDIT: Thanks for the tip, Jhon Pedroza!
EDIT: Noah B has pointed out that the above is dirty and inefficient. They are entirely correct. Better version based on their suggestion, credit to them:
function endpointsToOneString() {
let response1 = '', response2 = ''; // this line declares the local variables
const Http = new XMLHttpRequest();
const url = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
Http.open("GET", url);
Http.send();
Http.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
response1 = Http.responseText; //save one string
checkResults(response1, response2);
}
}
const HttpTwo = new XMLHttpRequest();
const urlTwo = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
HttpTwo.open("GET", urlTwo);
HttpTwo.send();
HttpTwo.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
response2 = HttpTwo.responseText; // save the other string
checkResults(response1, response2);
}
}
}
function checkResults(r1, r2) {
if (r1 != '' && r2 != '') {
console.log(r1 + r2);
}
}
endpointsToOneString();
function endpointsToOneString() {
var response;
const Http = new XMLHttpRequest();
const url = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
Http.open("GET", url);
Http.send();
Http.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
response = this.responseText;
HttpTwo.open("GET", urlTwo);
HttpTwo.send();
}
}
const HttpTwo = new XMLHttpRequest();
const urlTwo = 'https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json';
HttpTwo.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
response += this.responseText;
console.log(response);
}
}
}
endpointsToOneString();
check this out. there's just minimal editing to your code.

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);
}

Categories

Resources