Foreach element Javascript json - javascript

I got a JSON like this:
{
"email.com": ["email#email.com|username\r"],
"email.de": ["email#email.de|username"]
}
I want to get it printet like this:
email.com
email.de
var data = '{"email.com":["email#email.com|username\r"],"email.de":["email#email.de|username"]}';
var obj = JSON.parse(data);
for (i = 0; i < obj.length; i++) {
document.getElementById('types').innerHTML += '<br>' + obj[i]; // I want to get email.com , email.de
}
<div id="types">
</div>

This works fine:
var data = '{"email.com":["email#email.com|username\\r"],"email.de":["email#email.de|username"]}';
var obj = JSON.parse(data);
var keys = Object.keys(obj);
for (i = 0; i < keys.length; i++) {
document.getElementById('types').innerHTML += '<br>' + keys[i]; // I want to get email.com , email.de
}
<div id="types"></div>

var data = [{"email.com":["email#email.com|username\r"],"email.de":["email#email.de|username"]}];
var term = (Object.keys(data[0])[0]);
var obj = JSON.parse(data);
for (i = 0; i < obj.length; i++) {
document.getElementById('types').innerHTML += '<br>' + obj[i][term]; // I want to get email.com , email.de
}
This should work
Printing object's keys and values

Simple solution using String.match and Array.join functions:
var data = '{"email.com":["email#email.com|username\r"],"email.de":["email#email.de|username"]}',
emails = data.match(/\w+\.\w+(?=\":\[)/g).join("<br>");
document.getElementById('types').innerHTML += '<br>' + emails;
// 'emails' variable contains "email.com<br>email.de"
<div id="types"></div>

quickly :
var obj = {
"email.com": ["email#email.com|username\r"],
"email.de": ["email#email.de|username"]
};
for (var prop in obj) console.log(prop);

Related

Cannot read property 'split' of null

I cannot display all the results because on the following channel there is no image and therefore I have the following message
$.get('https://wcf.tourinsoft.com/Syndication/3.0/cdt33/c616ab2a-1083-4ba0-b8e2-f7741e443e46/Objects?$format=json', function(data) {
//$.get('/json/ecranv2.json', function(data){
var blogs = data.value;
$(blogs).each(function() {
var manifs = this.Listingraisonsociale;
var ouverturecomp = this.Listinginformationsouverture;
var commune = this.Listingcommune;
var ouverture = this.Listingouverture;
var photos = this.Listingphotos;
//var datatest= this.Listingphotos;
let output = '';
let users = this.Listingphotos.split('$');
//var testsplit = split($);
for (var i = 0; i < users.length; i++) {
console.log(users[i]);
output += '<img src=' + users[i] + '?width=150&height=150&crop=1>';
}
$('.target').append('<p>' + manifs + '</p><span>' + output + '</span>');
});
});
The one index does not have a value for the property. It is null, so you need to check to see if it is null before you try to use split on it. A simple truthy check will work in this case.
let users = this.Listingphotos ? this.Listingphotos.split('$') : [];
With it in place:
$.get('https://wcf.tourinsoft.com/Syndication/3.0/cdt33/c616ab2a-1083-4ba0-b8e2-f7741e443e46/Objects?$format=json', function(data) {
//$.get('/json/ecranv2.json', function(data){
var blogs = data.value;
$(blogs).each(function() {
console.log(this);
var manifs = this.Listingraisonsociale;
var ouverturecomp = this.Listinginformationsouverture;
var commune = this.Listingcommune;
var ouverture = this.Listingouverture;
var photos = this.Listingphotos;
//var datatest= this.Listingphotos;
let output = '';
let users = this.Listingphotos ? this.Listingphotos.split('$') : [];
//var testsplit = split($);
for (var i = 0; i < users.length; i++) {
console.log(users[i]);
output += '<img src=' + users[i] + '?width=150&height=150&crop=1>';
}
$('.target').append('<p>' + manifs + '</p><span>' + output + '</span>');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="target"></div>
split is a method on string objects, which will be called on an actual string's reference.
So in your case, the split is not being called on a string, and the error message clearly states that we are using split over a null object. So make sure the object you are working on is an actual string, and work on it accordingly.
split mdn

JSON input string error using $.ajax

My web API accepts below JSON format (this is input parameter)
[{
"atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe",
"atrSpaClassLegendId": "00D18EECC47E7DF44200011302",
"atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"},
{
"atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe",
"atrSpaClassLegendId": "00D18EECC47E7DF44200011302",
"atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"
}
]
I am building request below in javascript.
var administratorId = '47fe8af8-0435-401e-9ac2-1586c8d169fe'
var districtId = '144d0d78-c8eb-48a7-9afb-fceddd55622c'
var atrUserLegendsInputs
for (i = 0; i < list.get_items().get_count() ; i++)
{
atrUserLegendsInputs += { atrSpaUserId: administratorId, atrSpaClassLegendId: list.getItem(i).get_value(), atrSpaCityDistrictId: districtId } + ',';
}
atrUserLegendsInputs = atrUserLegendsInputs.substring(0, atrUserLegendsInputs.length - 1);
var legendIds = '[' + atrUserLegendsInputs + ']';
var atrDistrictLegend = { districtID: cityDistrictId, legendIDs: legendIds };
var test = JSON.stringify(atrDistrictLegend);
getting error message:
{["The input was not valid."]}
I am not sure whether I am doing the right way. I am new to Json and ajax calls. Can you one please help me to fix this issue
Try this code
var administratorId = '47fe8af8-0435-401e-9ac2-1586c8d169fe';
var districtId = '144d0d78-c8eb-48a7-9afb-fceddd55622c';
//* create empty array for legends
var atrUserLegendsInputs = [];
for (i = 0; i < list.get_items().get_count() ; i++) {
//* put some values into legends' array
atrUserLegendsInputs.push({
atrSpaUserId: administratorId,
atrSpaClassLegendId: list.getItem(i).get_value(),
atrSpaCityDistrictId: districtId
});
}
var atrDistrictLegend = {
districtID: cityDistrictId,
legendIDs: atrUserLegendsInputs
};
var test = JSON.stringify(atrDistrictLegend);

How to search for an array of patterns in another array using Google Script?

Using two arrays, I want to find patternArray[] items in myArray[].
If there is a match, I want to add the match from myArray to foundArray.
My current code gives me the following error;
TypeError: Cannot call method "search" of undefined. (line
could any one tell me how to fix the above error ?Furthermore, Does this solution find multiple matches in myArray ?
(for example if "red apple"(from patternArray) found more then once in myArray i want to add both to foundArray.)
function findpattern()
{
var foundArray=[];
var NotfoundArray=[];
var foundStringCounter=0;
var NotfoundStringCounter=0;
var myArray=["red apple http://awebsite.com/1.jpg","green apple http://1awebsite.com/2.jpg","red apple http://1awebsite.com/3.jpg"];
var patternArray= ["green apple","red apple","mango","orange tree","cherry tree","banana store","grape tree"];
var patternArraySize = patternArray.length;
for (var i = 0; i < patternArraySize; i++)
{
var result = myArray[i].search(patternArray[i]);
//var result = myArray[i].indexOf(patternArray[i]);
if (result == -1) {
NotfoundArray.push(myArray[i]);
NotfoundStringCounter++;
} else {
foundArray.push(myArray[i]);
foundStringCounter++;
}
result="";
}
Logger.log(foundStringCounter);
Logger.log(foundArray);
Logger.log(NotfoundStringCounter);
Logger.log(NotfoundArray);
}
This code works:
function findpattern() {
var foundArray=[],
NotfoundArray=[],
foundStringCounter=0,
NotfoundStringCounter=0;
var myArray=["red apple http://awebsite.com/1.jpg",
"green apple http://1awebsite.com/2.jpg",
"red apple http://1awebsite.com/3.jpg",
"rotten apple http://rottenApple.com"];
var patternArray= ["green apple","red apple","mango","orange tree","cherry tree","banana store","grape tree"];
var patternArraySize = patternArray.length;
Logger.log('patternArraySize: ' + patternArraySize);
var i=0,
j=0,
thisUrl="",
thisPattern="",
isMatched=0,
outerArray = [];
for (i=0; i < myArray.length; i++) {
thisUrl = myArray[i];
foundStringCounter = 0; //Reset
temporaryArray = []; //Reset
for (j=0; j<patternArraySize; j+=1) {
thisPattern = patternArray[j];
isMatched = thisUrl.indexOf(thisPattern);
if (isMatched !== -1) {
foundArray.push(thisUrl);
foundStringCounter++;
};
};
if (foundStringCounter===0) {
NotfoundArray.push(thisUrl);
};
outerArray.push(foundArray);
};
Logger.log('foundArray: ' + foundArray);
Logger.log('NotfoundArray: ' + NotfoundArray);
Logger.log('outerArray: ' + outerArray);
};
var currentSheet = SpreadsheetApp.getActiveSheet();
currentSheet
.getRange(currentSheet.getLastRow()+1, 1,outerArray.length,foundArray.length)
.setValues(outerArray);

Comparring Arrays with For Loops

Alright so I have been working on this one for a bit. I'm comparing the values of two arrays using a For Loop. Every time the array known as cart hits a number that can be found in the products array, it displays the info of the products array, for each time it is hit. I think my code itself is fine ( though I could be wrong) but it's not displaying the values. So I think there's something wrong with my execution of said process there. The codes as follows
function Fill(){
var txt=""
var products = new Array();
products[0] = {name: "refrigerator" , price:88.99, img:"img/refrigerator.jpg"};
products[1] = {name: "microwave oven" , price: 76.99 , img:"img/microwave.jpg"};
products[2] = {name: "dishwasher" , price:276.67 , img:"img/dishwasher.jpg"};
var carts = new Array ();
carts[0]= 2;
carts[1]= 0;
carts[2]= 1;
carts[3]= 1;
carts[4]= 0;
carts[5]= 1;
carts[6]= 2;
carts[7]= 2;
for(var i=0; i < carts.length; i++){
for(var j = 0; j < products.length; j++){
if(carts[i] == j){
txt +=products[j].name + ' ' + products[j].price +" <img src='"+ products[j].img + "'>"
document.getElementById("answer").innerHTML += txt
}
}
}
}
Update answer with ES6:
const products=[{name:"refrigerator",price:88.99,img:"img/refrigerator.jpg"},{name:"microwave oven",price:76.99,img:"img/microwave.jpg"},{name:"dishwasher",price:276.67,img:"img/dishwasher.jpg"}];
const carts=[2,0,1,1,0,1,2,2];
const productsInCart = [...new Set(carts)]
.reduce((a,c)=>{
a.set(c,products[c])
return a;
}, new Map());
const res = carts.map(c=>{
const {name, price, img} = productsInCart.get(c)
return `${name} ${price} <img src="${img}"/>`;
}).join("");
document.body.innerHTML = res;
You should be comparing carts[i] with j otherwise you won't find anything
var txt = ""
var products = new Array();
products[0] = {
name: "refrigerator",
price: 88.99,
img: "img/refrigerator.jpg"
};
products[1] = {
name: "microwave oven",
price: 76.99,
img: "img/microwave.jpg"
};
products[2] = {
name: "dishwasher",
price: 276.67,
img: "img/dishwasher.jpg"
};
var carts = new Array();
carts[0] = 2;
carts[1] = 0;
carts[2] = 1;
carts[3] = 1;
carts[4] = 0;
carts[5] = 1;
carts[6] = 2;
carts[7] = 2;
for (var i = 0; i < carts.length; i++) {
for (var j = 0; j < products.length; j++) {
if (carts[i] == j) {
txt = products[j].name + ' ' + products[j].price + " <img src='" + products[j].img + "'>"
document.getElementById("answer").innerHTML += txt
}
}
}
<div id="answer"></div>
Your txt variable should be modified with = and not +=
You should optimize your code. document.getElementById("answer") could be initiated globally for example.
"carts" is an array of numbers (as per your source code) while "products" is an array of objects. So your condition "carts[i] == products[j]" will never fire.
What's the value of your appliance variable?
It'll cause the code to error out.
To also steal Alex's answer: "carts" is an array of numbers (as per your source code) while "products" is an array of objects. So your condition "carts[i] == products[j]" will never fire.
Perhaps this is better?..
carts[7]= 2;
for(var i=0; i < carts.length; i++){
txt +=products[carts[i]].name + ' ' + products[carts[i]].price +" <img src='"+ products[carts[i]].img + "'>"
document.getElementById("answer").innerHTML += txt
}
Upvoting Grimbode's answer as it's pretty close to mine, but cleaner.
I'm not sure why you need the second for loop. You're trying to compare a number with a product object by doing this and it will never work. OK, assuming that what you are trying to achieve is that if carts[0]=2 you want the info for products[2] then try something like:
for(i=0; i<carts.length; i++) {
if(i<products.length) {
currProd=products[carts[i]];
//Process the currProd object as you will
}
}

Use for loop to create mulitiple variables?

I want to use for loop to create multiple variables.
I want to create
var node0 = document.getElementById("refresh_table_0");
node0.innerHTML="";
var node1 = document.getElementById("refresh_table_1");
node1.innerHTML="";
var node2 = document.getElementById("refresh_table_2");
node2.innerHTML="";
this is my imagination code:
for(i=0;i<3;i++){
var node+i = document.getElementById("refresh_table_i");
node+i.innerHTML="";
}
First, this is javascript.
Second, the imagined code has errors, should be ("refresh_table_" + i).
Try using js arrays instead.
var node = new Array();
for(i=0;i<3;i++){
node[i] = document.getElementById("refresh_table_" + i);
node[i].innerHTML="";
}
To just initialize all the items, you can simply do this as there's no need to retain each separate DOM object:
var node;
for (var i = 0; i < 3; i++) {
node = document.getElementById("refresh_table_" + i);
node.innerHTML = "";
}
Or, even just this:
for (var i = 0; i < 3; i++) {
document.getElementById("refresh_table_" + i).innerHTML = "";
}

Categories

Resources