javascript increment name of variable - javascript

I get an object with partial results of match from database.
[Object { home1=4, away1=3, home2=4, away2=5, home3=6, away3=7, home4=6, away4=5, home5=3, away5=6}]
home1 it's a result of first part of home team,
away1 -> away team, home2 it's a result of second part of home team... etc etc
data in my case is each row, which i get from database.
In rows i have td with class: home1, home2, home3, away1, away2 and there are values of corresponding part of match.
I want to check if value is equal to what I got from database.
Something like this
if ($('.home1') === data[index].home1;
if($('.away2') === data[index].away2;
there should be some loop. I have no idea how to do this, I thought about an array
var array = [
{
home1: data[index].home1,
away1: data[index].away1
},
{
home2: data[index].home2,
away2: data[index].away2
},
{
home3: data[index].home3,
away3: data[index].away3
},
{
home4: data[index].home4,
away4: data[index].away4
},
{
home5: data[index].home5,
away5: data[index].away5
}
]
and then for loop:
for(var X=0; X<5;X++){
homeX == data[index].homeX
}
How can I increment name of variable by eval function? or is there any other solution? I'm very confused.

You can access object properties using operator []:
for(var i=0; i<array.length; i++)
{
var item = array[i];
var homePropertyName = 'home' + (i+1);
//now you can access homeX property of item using item[homePropertyName]
//e.g. item[homePropertyName] = data[index][homePropertyName]
}

Maybe you should use a little different structure which might fit your needs better, like this:
array = [
0: array [
"home": "Text for home",
"away": "Text for away"
],
1: array [
"home": "",
"away": ""
]
// More sub-arrays here
];
You can also initialize it with a for loop:
var array = new Array();
var i;
for (i = 0; i < 4; i++) {
array[i] = [
"home": "",
"away": ""
];
}
Or like this:
array[0]["home"] = "Text for home";
array[0]["away"] = "Text for away";
You can use this structure for the data-array also, and then use a for-loop to go through them both (like if you wish to find an element):
var result = NULL;
for (i = 0; i < array.length; i++) {
if ( (array[i]["home"] == data[index]["home"]) &&
(array[i]["away"] == data[index]["away"])
) {
// Found matching home and away
result = array[i];
break;
}
}
if (result != NULL) {
alert("Found match: " + result["home"] + " - " + result["away"]);
}
else {
alert("No match");
}
PS: Code is not tested, let me know if something is wrong.

you can access global properties in browser via window object like this (fiddle):
value1 = "ONE";
alert( window['value'+1] );
But it is not good design. You should look into how to properly format JSON object.

I have something like this:
for(var i=0; i<2; i++)
{
var item = ARR[i];
for(var x=0;x<5;x++){
var hPropertyName = 'home_p' + (x+1);
var aPropertyName = 'away_p' + (x+1);
item[hPropertyName] = ARR[i][hPropertyName];
item[aPropertyName] = ARR[i][aPropertyName];
}
and it works when i create an array:
var ARR = [
{
home_p1: 4,
away_p1: 5,
home_p2: 8,
away_p2: 9,
home_p3: 2,
away_p3: 1,
home_p4: 5,
away_p4: 3,
home_p5: 3,
away_p5: 2
},
{
home_p1: 6,
away_p1: 1,
home_p2: 1,
away_p2: 2,
home_p3: 3,
away_p3: 4,
home_p4: 5,
away_p4: 6,
home_p5: 3,
away_p5: 2
}
];
but I don't have to create an array, because i have to work on object which I get from database :
[Object { event_id=19328, home_result=3, away_result=2, home_p1=4, away_p1=3, home_p2=1, away_p2=2 ...... }]
I'm only interested in these parameters --> home_p , away_p
I want to push it to my array to looks like ARR. I think i should convert an object which I get to an array

If you are using string name for your attributes then you could try using template literals?
var someObject = {}
for(let i=0 ; i<values.length ; i++){
someObject[`home${i+1}`] = values[i];
}
and if you need it to be ES5 you could just use string concatenation. Below is a working example:
values = [1,2,3,4,5];
let someObject = {};
for(let i=0 ; i<values.length ; i++){
someObject[`value${i+1}`]=values[i];
}
console.log(someObject.value1);
console.log(someObject.value2);
console.log(someObject.value3);
console.log(someObject.value4);
console.log(someObject.value5);

Related

Count and loop through JSON object of arrays

I get issues when I want to loop through a JSON array of objects.
Issues such as:
It only counts two (I assume because of they Object.keys) and I have two keys.
Loops with only one value
My code:
var codes = require('./nl.json');
for (var i = 0, l = Object.keys(codes).length; i <= l; i++) {
console.log(l) ;
var areaCodeTest = codes.netherlands[i].areaCode;
var areaNameTest = codes.netherlands[i].areaName;
it("Search for postal code ", function(){
var postCode = element(by.id("imysearchstring"));
postCode.click();
browser.sleep(1000);
console.log(areaCodeTest);
postCode.clear().sendKeys(areaCodeTest);
browser.sleep(1000);
console.log("Typed " + areaCodeTest);
});
}
My Json (Short example):
{
"netherlands": [
{
"areaCode": 9401,
"areaName": "Assen"
},
{
"areaCode": 9402,
"areaName": "Assen"
},
{
"areaCode": 9403,
"areaName": "Assen"
}
]
}
I have looked at answers such as :
Size of Object and
Length of Json
I have tried:
(var i = 0, l = Object.keys(codes).length; i <= l; i++)
(var i = 0, l = Object.keys(codes.netherlands[0]).length; i <= l; i++)
for (var i = 0, l = codes.netherlands.length; i <= l; i++) // uses last areaCode in json file and only loop with that number. It does not start from top.
Image:
some of my outputs
Expected:
What I want is to count amount of ofjects in JSON (Not the key/values)
Loop through all data and assign them to var areaCodeTest = codes.netherlands[i].areaCode; and var areaNameTest = codes.netherlands[i].areaName;
I got it to work by using the following:
var codes = require('./nl.json');
codes.forEach((item) => {
var areaCodeTest = item.areaCode;
var areaNameTest = item.areaName;
it("and search for postal code ", function(){
var postCode = element(by.id("imysearchstring"));
postCode.click();
console.log(areaCodeTest);
postCode.clear().sendKeys(areaCodeTest);
browser.sleep(1000);
console.log("Typed " + areaCodeTest);
});
}
I am not a 100% what the => means near the foreach but I am currently researching why my code works. If you know please post a comment so that other developers also learn.
This let me think of the meme "not sure why code does not work / Not sure why code works"
You need to access the actual key in your loop in order to access codes[key]
Simplified version of your for() loop with stored variable for the object keys or using for in loop
const keys = Object.keys(codes)
for (let i = 0; i < keys.length; i++) {
// current object key and value of that property in main object
const key = keys[i], arr = codes[key];
console.log(`key = ${key}, length= ${arr.length}`)
// do another loop here for `arr` if needed
}
// OR using `for in`
for (let key in codes) {
console.log(`key = ${key}, length= ${codes[key].length}`)
}
<script>
const codes = {
"netherlands": [{
"areaCode": 9401,
"areaName": "Assen"
},
{
"areaCode": 9402,
"areaName": "Assen"
},
{
"areaCode": 9403,
"areaName": "Assen"
}
]
}
</script>
Try this I give you a sample
const object1 = {
a: 'somestring',
b: 42,
c: false
};
var length = (Object.keys(object1).length);
Please Refer this Link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Change the format of search result from JSON file

I am using javascript to search content from JSON file, below is my code:
var result = [];
var searchField = "equip_id";
for (var i=0 ; i < jsondata.array.length ; i++)
{
if (jsondata.array[i][searchField] == SelectedEquip) {
result.push(jsondata.array[i].group_name);
}
}
And the output is a group name with the following format:
["groupname"]
I only want the groupname without [] and "". Because I need to use the groupname to search another JSON file.
Anyone can help solve this problem?
If you want the result as a string, how about:
// Sample Data
var jsondata = {
array: [{
equip_id: 1,
group_name: "a"
}, {
equip_id: 2,
group_name: "b"
}, {
equip_id: 3,
group_name: "c"
}]
}, SelectedEquip = 3;
// Actual code
var result = '';
var searchField = "equip_id";
for (var i = 0; i < jsondata.array.length; i++) {
if (jsondata.array[i][searchField] == SelectedEquip) {
result = jsondata.array[i].group_name;
}
}
// Sample output
console.log(result);
Using your code above, result[0] will give you the same output. There's just no need to create and push to an array, if you are dealing with a single value.

How to iterate over an array in an array

I want to iterate over my 'areasarray' in the array 'areas' dataprovider array,
I have no idea how to loop over an array in an array, I've tried several tries with for-loops but none of it succeeded.
this is amCharts Maps framework.
var areasarray = {};
//get JSON File
$(function getData() {
var url = "../assets/document.json";
$.ajax({
url: url,
dataType: 'json',
success: function (data) {
console.log(data);
for (var i = 0; i < data.fact.length; i++) {
if (inverseCountryCodes[data.fact[i].dims.COUNTRY] != null) {
areasarray[i] = {
"id": inverseCountryCodes[data.fact[i].dims.COUNTRY],
"value": data.fact[i].Value,
"info": "Verkeersdoden per 100 000 inwoners: " + data.fact[i].Value
}
}
}
//console.log(areasarray);
//Map initialiseren
var map;
map = new AmCharts.AmMap();
map.colorSteps = 20;
var dataProvider =
{
mapVar: AmCharts.maps.worldLow
areas: [
{
id: "BE",
value: 10,
info: "Verkeersdoden ..."
}
]
};
console.log(dataProvider);
map.areasSettings = {
autoZoom: true,
selectedColor: "#338DAB"
};
map.dataProvider = dataProvider;
var valueLegend = new AmCharts.ValueLegend();
valueLegend.right = 10;
valueLegend.minValue = "little";
valueLegend.maxValue = "a lot!";
map.valueLegend = valueLegend;
map.addListener("clickMapObject", function (event) {
document.getElementById("info").innerHTML = '<p><b>' + event.mapObject.title + '</b></p><p>' + event.mapObject.info + '</p>';
});
map.mouseWheelZoomEnabled = true;
map.write("mapdiv");
}
});
});
If you want to iterate over areasarray which is actually an object and not an array you should look into using a for...in loop
For iterating over arrays within arrays, one approach would be to nest for loops
for(var i = 0; i < array1.length; i++) {
for(var j = 0; j < array2.length; j++) {
// do something
}
}
It's not clear to me what you mean by "array in an array" in this context and it would help if you provided more information about what exactly you are trying to accomplish
I would try a nested loop. Here is an example of creating an array of arrays and then looping through each.
var matrix = []
matrix[1] = []
matrix[1][1] = "foo"
matrix.forEach(function(column){
column.forEach(function(cell){
console.log(cell);
});
});
var areasarray = {}; means it's an object, not an array.
To iterate through each items in this object, try this.
var keys = Object.keys(areasarray);
keys.forEach(function(k) {
// you can access your item using
// k is the property key
console.log(areasarray[k]);
console.log(areasarray[k].id);
console.log(areasarray[k].value);
console.log(areasarray[k].info);
});
Not sure why you chose to create areasarray as an object.
If you wanted to, you could have defined it as:
var areasarray = [];
Then when adding to the array you use:
areasarray.push({
"id": inverseCountryCodes[data.fact[i].dims.COUNTRY],
"value": data.fact[i].Value,
"info": "Verkeersdoden per 100 000 inwoners: " + data.fact[i].Value
});
So later on, you can simply do:
for (var i = 0; i < areasarray.length; i++) {
console.log(areasarray[i]);
console.log(areasarray[i].id);
console.log(areasarray[i].value);
console.log(areasarray[i].info);
}
Note: in the above code, i is an index, where in the object block code, k is a key to the object.
Use nested loops.
Example:
var a1=["1","2","3","4","5","6","7"];
var a2=["a","b","c","d","e"];
for(var i=0;i<a1.length;i++) //loop1
{
console.log(a1[i]);
for(var j=0;j<a2.length;j++) //loop2
{
console.log(a2[j]);
}
}
Sample Output:
1st iteration of loop1:
1abcde
2nd iteration of loop1:
2abcde
and so on...
For every iteration of loop1,loop2 iterates 4 times(j<5).
Hoping I got your question right...This could be an answer.!

get values in pairs from json array

Firstly, this is my json value i am getting from a php source:
[{"oid":"2","cid":"107"},{"oid":"4","cid":"98"},{"oid":"4","cid":"99"}]
After that, I want to get and oid value along with the corresponding cid value for example, oid=2 and cid=107 at one go, oid=4 and cid=98 at another and so on. I am trying to use jquery, ajax for this.
I have tried many answers for this, like: Javascript: Getting all existing keys in a JSON array and loop and get key/value pair for JSON array using jQuery but they don't solve my problem.
I tried this:
for (var i = 0; i < L; i++) {
var obj = res[i];
for (var j in obj) {
alert(j);
}
but all this did was to return the key name, which again did not work on being used.
So, you have an array of key/value pairs. Loop the array, at each index, log each pair:
var obj = [{"oid":"2","cid":"107"},{"oid":"4","cid":"98"},{"oid":"4","cid":"99"}];
for (var i = 0; i < obj.length; i++) {
console.log("PAIR " + i + ": " + obj[i].oid);
console.log("PAIR " + i + ": " + obj[i].cid);
}
Demo: http://jsfiddle.net/sTSX2/
This is an array that you have //lets call it a:
[{"oid":"2","cid":"107"},{"oid":"4","cid":"98"},{"oid":"4","cid":"99"}]
To get first element :
a[0] // this will give you first object i.e {"oid":"2","cid":"107"}
a[0]["oid"] // this will give you the value of the first object with the key "oid" i.e 2
and so on ...
Hope that helps.
`
Basically what you need is grouping of objects in the array with a property. Here I am giving two functions using which you can do this
// To map a property with other property in each object.
function mapProperties(array, property1, property2) {
var mapping = {};
for (var i = 0; i < data.length; i++) {
var item = data[i];
mapping[item[property1]] = mapping[item[property1]] || [];
mapping[item[property1]].push(item[property2]);
}
return mapping;
}
// To index the items based on one property.
function indexWithProperty(array, property) {
var indexing = {};
for (var i = 0; i < data.length; i++) {
var item = data[i];
indexing[item[property]] = indexing[item[property]] || [];
indexing[item[property]].push(item);
}
return indexing;
}
var data = [{
"oid": "2",
"cid": "107"
}, {
"oid": "4",
"cid": "98"
}, {
"oid": "4",
"cid": "99"
}];
var oidCidMapping = mapProperties(data, "oid", "cid");
console.log(oidCidMapping["2"]); // array of cids with oid "2"
var indexedByProperty = indexWithProperty(data, "oid");
console.log(indexedByProperty["4"]); // array of objects with cid "4"
May not be the exact solution you need, but I hope I am giving you the direction in which you have to proceed.
If you are willing to use other library you can achieve the same with underscorejs

Setting up a variable length two-dimensional array

I have a string as follows :
Panther^Pink,Green,Yellow|Dog^Hot,Top
This string means I have 2 main blocks(separated by a '|') :
"Panther" and "Dog"
Under these two main blocks, I have, lets say "subcategories".
I wanted to create a 2-dimensional array represented (in logic) as follows :
Panther(Array 1) => Pink(Element 1),Green(Element 2), Yellow(Element 3)
Dog(Array 2) => Hot(Element 1), Top(Element 2)
Also,I want to be able to add a main block, lets say "Cat" with possible categories "Cute,Proud" to the two dimensional array
I've managed to get an Array containing "Panther^Pink,Green,Yellow" and "Dog^Hot,Top" by using JavaScript's split function.
Note that this string is received via Ajax and can be of any length, though the format shown above is always used.
----------------------------- EDIT ----------------------------
Ok, my script so far is :
$(document).ready(function(){
appFunc.setNoOfAppBlock('Panther^Pink,Green,Yellow|Dog^Hot,Top');
appFunc.alertPing();
});
var appFunc = (function(stringWithSeper) {
var result = {},
i,
categories = new Array(),
subcategories;
return {
setNoOfAppBlock: function(stringWithSeper){
categories = stringWithSeper.split("|");
for (i = 0; i < categories.length; i++) {
subcategories = categories[i].split("^");
result[subcategories[0]] = subcategories[1].split(",");
}
},
alertPing: function(){
alert(result["Panther"][1]);
}
};
})();
However, the function "alertPing" isn't "alerting" anything.What am am I doing wrong ?
To me the most logical representation of your data:
Panther^Pink,Green,Yellow|Dog^Hot,Top
Is with a JavaScript object with a property for each category, each of which is an array with the subcategories:
var data = {
Panther : ["Pink", "Green", "Yellow"],
Dog : ["Hot", "Top"]
}
You would then access that by saying, e.g., data["Dog"][1] (gives "Top").
If that format is acceptable to you then you could parse it as follows:
function parseData(data) {
var result = {},
i,
categories = data.split("|"),
subcategories;
for (i = 0; i < categories.length; i++) {
subcategories = categories[i].split("^");
result[subcategories[0]] = subcategories[1].split(",");
}
return result;
}
var str = "Panther^Pink,Green,Yellow|Dog^Hot,Top";
var data = parseData(str);
Assuming you're trying to parse your data into something like this:
var result = {
Panther: ["Pink", "Green", "Yellow"],
Dog: ["Hot", "Top"]
}
you can use string.split() to break up your string into subarrays:
var str = "Panther^Pink,Green,Yellow|Dog^Hot,Top";
var result = {}, temp;
var blocks = str.split("|");
for (var i = 0; i < blocks.length; i++) {
temp = blocks[i].split("^");
result[temp[0]] = temp[1].split(",");
}
Data can then be added to that data structure like this:
result["Cat"] = ["Cute", "Proud"];
Data can be read from that data structure like this:
var dogItems = result["Dog"]; // gives you an array ["Hot", "Top"]
You can use something like:
function parseInput(_input) {
var output = [];
var parts = _input.split('|');
var part;
for(var i=0; i<parts.length; i++) {
part = parts[i].split('^');
output[part[0]] = part[1].split(',');
}
return output;
}
Calling parseInput('Panther^Pink,Green,Yellow|Dog^Hot,Top'); will return:
output [
"Panther" => [ "Pink", "Green", "Yellow" ],
"Dog" => [ "Hot", "Top" ]
]
To add another item to the list, you can use:
output["Cat"] = ["Cute", "Proud"];

Categories

Resources