retrieving specific data from json array using javascript - javascript

Hi guys need a little help here since I am a begiiner in javascript Please note that my question might be a duplicate to you all but I need a little enlightenment here, anyway I need to get to display the data I need from a JSON array lets say I have 3 array
var = countrysites[ "Denmark"],["United States"],["France"]
if I click the marker for Denmark using basic javascript Onclick it would display the data for Denmark only not calling all data of USA and France. Here is my javascript code
function displayData(){
for (var i = 0; i < countrysites.length; i++) {
if (countrysites[i].country_name === id) {
countrysites[i].country_name = country_name;
}
}
}
and my div has an id of 'sitemark' and has onclick of displayData
Thank you in advance

If you're going to be going through a multi-dimensional array you'd have to use two for loops like so
for(var i = 0; i < arr.length; i++) {
for(var j = 0; j < arr[i].length; j++) {
if(whatever you're looking for) {
}
}
}

I've taken some liberties in answering this because I'm still not sure what your data-structure looks like, but hopefully this will help.
Here's the data you're receiving as JSON which you then parse. It's array of objects each of which contains country_name and info properties.
const countryInfo = [
{ country_name: 'Denmark', info: 'This is Denmark' },
{ country_name: 'England', info: 'This is England' },
{ country_name: 'Japan', info: 'This is Japan' }
];
For the purposes of this DEMO we grab the body element, and then grab an array of just the country names from the data.
const body = document.querySelector('body');
const names = countryInfo.map(obj => obj.country_name);
We build some markers with that array data and add them to the body element. Note the data attribute data-name. We store a copy of the country name here.
names.forEach(name => {
const html = `<div class="sitemark" data-name="${name}">${name}</div>`;
body.insertAdjacentHTML('beforeend', html);
});
We grab the info element. This is where we add the country information.
const info = document.querySelector('#info');
We grab the markers and add event listeners to them. When one is clicked, call the displayData function.
const sitemarks = document.querySelectorAll('.sitemark');
sitemarks.forEach(marker => {
marker.addEventListener('click', displayData, false);
});
To get the countryinfo we perform a find operation on the countryInfo array that pulls out the first object instance where the country name is the same as the name in the data-name attribute on the element, and then take the info value from that object. Then we add that text to the info element.
function displayData() {
const text = countryInfo.find(obj => obj.country_name === this.dataset.name).info;
info.innerHTML = text;
}

Related

Replicating MySQL array formatting in Javasript

I have 5 mysql tables that i need a variety of data from in several different scripts that all reference each other using an id's located in 1 or more column.
I need to create a master query that replicates the array structure exactly as it was imported from mysql AND ALSO needs error handling for each field before it writes to an array to determine if it needs to write the value to an array, or write it as null.
So far the script is looking like this:
const items = [];
// Items
for (let i = 0; i < gameItems.length; i++) {
if (gameItems[i].id) {
items.push({ id: gameItems[i].id });
} else {
items.push({ id: null });
}
if (gameItems[i].identifier) {
items.push({ identifier: if (gameItemParams[i].custom_name)
{
items.push({ custom_name: gameItemParams[i].custom_name });
}
else {
items.push({ custom_name: null }); }
}
}
The problem, or my lack of ability to figure out the logic on how to execute the code correctly, is that in order to attach multiple fields of data to the same row in an array the values must be comma separated.
Individual pushes like above add data to the next row instead of the same object which renders the array.length properly useless because there is a new row for every single field so instead of having 1 row with 10 pieces of data attached, i would have 10 rows each with 1 piece of data.
Is there a way to perform error handling for each field i need to call from the tables or is there another way to add data to the same object after a row has already been pushed.
This is how the newly created array must be structured:
https://puu.sh/E7ogn/61c3117d3b.png
This is how the array is currently being structured with individual pushes:
https://puu.sh/E7oh7/422541a70d.png
Maybe if it is possible to break in the middle of an array.push i can then add error handling in the push block but was unable to find if it can be done.
The problem is that you are pushing an object every time. Instead of that, you need to create an object with all of fields and then push it to the array.
Other problem of your code is that you can use an if statement into a assigment statement. You need to use a conditional operator to do that or extract this conditional from the assigment.
const items = [];
// Items
for (let i = 0; i < gameItems.length; i++) {
var object = {};
if (gameItems[i].id) {
object.id = gameItems[i].id;
}
else {
object.id = null;
}
if (gameItems[i].identifier) {
object.identifier = (gameItemParams[i].custom_name) ? items.push({ custom_name: gameItemParams[i].custom_name }); : items.push({ custom_name: null });
}
items.push(object);
}
As per the data mentioned in https://puu.sh/E7oh7/422541a70d.png.
You have data like
gameItems=[{id:0}, {identifier:"master-ball"}, {category_id:34}, {"custom_name":"Master Ball"}];
I suggest that instead of making items as an array, Please create temporary object item and then push it to items.
let items = [];
let item = {
id:null,
identifier: null,
custom_name: null
};
for (let i = 0; i < gameItems.length; i++) {
if (gameItems[i].id !== undefined) {
item.id = gameItems[i].id;
}
if (gameItems[i].identifier !== undefined) {
item.identifier = gameItems[i].identifier;
}
if (gameItems[i].custom_name !== undefined) {
item.custom_name = gameItems[i].custom_name;
}
}
items.push(item);

Updating the value of an object inside a loop using javascript

I'm currently facing a difficulty in my codes.
First i have an array of objects like this [{Id:1, Name:"AML", allowedToView:"1,2"}, {Id:2, Name:"Res", allowedToView:"1"}...] which came from my service
I assign it in variable $scope.listofResource
Then inside of one of my objects I have that allowedToView key which is a collection of Id's of users that I separate by comma.
Then I have this code...
Javascript
$scope.listofResource = msg.data
for (var i = 0; i < msg.data.length; i++) {
First I run a for loop so I can separate the Id's of every user in allowedToView key
var allowed = msg.data[i].allowedToView.split(",");
var x = [];
Then I create a variable x so I can push a new object to it with a keys of allowedId that basically the Id of the users and resId which is the Id of the resource
for (var a = 0; a < allowed.length; a++) {
x.push({ allowedId: allowed[a], resId: msg.data[i].Id });
}
Then I put it in Promise.all because I have to get the Name of that "allowed users" base on their Id's using a service
Promise.all(x.map(function (prop) {
var d = {
allowedId: parseInt(prop.allowedId)
}
return ResourceService.getAllowedUsers(d).then(function (msg1) {
msg1.data[0].resId = prop.resId;
Here it returns the Id and Name of the allowed user. I have to insert the resId so it can pass to the return object and it will be displayed in .then() below
return msg1.data[0]
});
})).then(function (result) {
I got the result that I want but here is now my problem
angular.forEach(result, function (val) {
angular.forEach($scope.listofResource, function (vv) {
vv.allowedToView1 = [];
if (val.resId === vv.Id) {
vv.allowedToView1.push(val);
I want to update $scope.listofResource.allowedToView1 which should hold an array of objects and it is basically the info of the allowed users. But whenever I push a value here vv.allowedToView1.push(val); It always updates the last object of the array.
}
})
})
});
}
So the result of my code is always like this
[{Id:1, Name:"AML", allowedToView:"1,2", allowedToView:[]}, {Id:2, Name:"Res", allowedToView:"1", allowedToView:[{Id:1, Name:" John Doe"}]}...]
The first result is always blank. Can anyone help me?
Here is the plunker of it... Plunkr
Link to the solution - Plunkr
for (var i = 0; i < msg.length; i++) {
var allowed = msg[i].allowedToView.split(",");
msg[i].allowedToView1 = [];
var x = [];
Like Aleksey Solovey correctly pointed out, the initialization of the allowedToView1 array is happening at the wrong place. It should be shifted to a place where it is called once for the msg. I've shifted it to after allowedToView.split in the first loop as that seemed a appropriate location to initialize it.

How to check if data being added to an array already exists in a different array?

I am looking to create a simple script for a Google sheet in which array 1 will already be populated with a list of names. As a new name gets added to array 2, array 1 is checked for the name. If the name which was entered into array 2 is present in array 1 an action will be performed. This search function must take place each time a new name is added to array 2 to determine if it exists in array 1.
function findPlayer() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var picksRange = ss.getRange("B2:M15");
var poolRange = ss.getRange("B21:G96");
var picksPlayerName = picksRange.getValues();
var poolPlayerName = poolRange.getValues();
for (var i = 0; i < picksRange.length; i++)
for (var j = 0; j < poolRange.lenth; j++)
if (picksPlayerName[i] == poolPlayerName[j]) {
poolPlayerName[i].setBackground("red")}
else {
poolPlayerName[j].setBackground("blue");}
}
This is not a complete answer, nor does it perfectly fit your use-case, but you should be able to take it from here, or perhaps come back with another question when you have a question about a specific part of your code.
const existingNames = ["Carl", "Emma", "Sarah", "Ahmad"];
const newNames = ["Emma", "Sarah", "Isa", "Igor", "Kent"];
// go through the new names and check against existing ones
newNames.forEach(newName => {
if(existingNames.includes(newName)) {
// handle duplicates: do nothing?
} else {
// handle new names: maybe add them to the existing names?
existingNames.push(newName);
}
});
console.log('After going through all new names, the complete list of known names are: ' + existingNames);
Demo where you can play with the code and learn: https://jsfiddle.net/jonahe/11uom4cu/

How can I dynamically index through datalayer tags in GTM?

I'm using the DuracellTomi datalayer plugin to push cart data from woocommerce to a GTM model to handle some tracking.
The DuracellTomi plugin pushes content to the transactionProducts[] array in the following format:
transactionProducts: Array[1]
0 : Object
category:""
currency:"USD"
id:8
name:"Test"
price:100
quantity:"1"
sku:8
I'd like to loop through this array and unstack it into three separate arrays, pricelist, skulist, and quantitylist. Currently I anticipate doing so as some variation on
//Get Product Information
if(stack = {{transactionProducts}}){
for(i = 0; i < stack.length; i++) {
if(stack.i.sku){
skulisttemp.i = stack.i.sku;
}
if(stack.i.price){
pricelisttemp.i = stack.i.price;
}
if(stack.i.sku){
quantitylisttemp.i = stack.i.quantity;
}
}
{{skulist}} = skulisttemp;
{{pricelist}} = pricelisttemp;
{{quantitylist}} = quantitylisttemp;
}
Obviously this is not going to work because of how the tag referencing is set up, but I'm wondering if anyone has dealt with this and knows what the best way to index through these arrays might be. (For those who don't know, the square bracket array call doesn't work with GTM variables and instead the . format is used instead.)
You would need to create 3 variable type custom javascript function that picks your required value from dataLayer and returns it in an array.
Something like
function(){
var products = {{transactionProducts}};
var skuArray = [];
for(i = 0; i < products.length; i++) {
if(products[i].sku){
skuArray.push(products[i].sku)
}
}
return skuArray
}
hope this helped you :)

Javascript -- How to find and replace text matched via nested array list?

I am trying to find text in all <p> tags, in document and replace the text if it is present in my search_array list:
search_array=[
['DBCONERROR01','Unable to Connect Database Server'],
['DBCONERROR02','Error Occured With DataBase Connection'],
['DBCONERROR03','Unable to Communicate with Data Base'],
['DBQRYERROR01','Invalid Query OR DataBase Error'],
['DBCONERROR04','Connection Lost with Database'],
['DBQRYERROR02','DataBase Query Failed'],
['DBQRYERROR03','Invalid to Wrong Sql Query'],
['TARIFERROR01','No Rates Found for Tariff'],
['AUTHSERROR01','Authentications not Found'],
['SWICHERROR01','Unable to Find Switch Details'],
['IOPRMERROR01','File Permission Error'],
['IOPRMERROR01','IO Error with operation System'],
['IOPRMERROR01','File Handling Error - Unable to Communicate with IO'],
['OPSSHERROR01','Unable to SSH switch - Connection Error'],
['OPSSHERROR02','SSH to Switch Failed'],
['OPSSHERROR03','Unable to Copy Scripts to Switch'],
['OPSSHERROR04','Unable to Execute Script on Switch'],
['JSONPERROR01','Unable to Parse Json'],
['TARIFERROR02','No Entry Found'],
['TARIFERROR03','Unable to Push Rates TO SBC'],
["DoesNotExist('Email does not exist.',)",'No Emails Received']
]
$( document ).ready(function() {
for(var i=0; i<search_array.length+1; i++)
{
console.log(i);
console.log(search_array.length);
for(var j=0; j<search_array[i].length; j++)
{
var str = $("p").text();
console.log(str[0]);
str.replace(search_array[j], search_array[j+1]);
}
}
});
This is what my code looks like, But I am still unable to perform task... Kindly help me.
The main problem is you don't reset the p elements' textContent, also .replace() method leaves the original string unchanged. You can use the text() method callback function, the callback is executed once for each selected element in the collection:
// var search_array = [ ... ];
$(document).ready(function() {
$('p').text(function(_, text) {
for (var i = 0; i < search_array.length; i++) {
text = text.replace(search_array[i][0], search_array[i][1]);
};
return text; // return the modified textContent
});
});
#BlackShape answers little bit modified version as following using each function:
// var search_array = [ ... ];
$(document).ready(function() {
$('p').text(function(_, text) {
$.each(search_array, function(index){
text = text.replace(search_array[index][0], search_array[index][1]);
});
return text; // return the modified textContent
});
});
Another drawback in #BlackShape's approach is search_array.length read multiple times inside for statement. If you want to use #BlackShape you can just read only one time and assign to local variable and use it inside of for loop statement.
for (var i = 0; i < search_array.length; i++)

Categories

Resources