Array in javascript like php - javascript

Hello guys I'm trying to make a array in javascript like I can make in php. In php i can make a array like this and then insert in whatever index I like
$p = array();
$p["abcd"] = "James";
Now I want this functionality in js. Is it possible to do it in js
I have done something like this but this is throwing me an error
$.each( $('table[data-step-id=' + step_id +'] input[name^=actions]') , function(key , value){
debugger;
steps_actions_dates_assign[key]["action"].push(value.val());
});
this is the error
Uncaught TypeError: Cannot set property 'action' of undefined
MY QUESTION IS NOT A DUPLICATE
I'm not trying to access a php array in javascript but I'm trying to make a array in javascript like php(the way we do not have to worry about indexes the same way I should be able to add any index I want)
THIS IS ALL OF THE CODE
var steps_actions_dates_assign = new Array();
$.each($('.steps-table') , function (key , value){
debugger;
step_id = value.children[0].value;
steps_actions_dates_assign[key]["action"] = new Array();
$.each( $('table[data-step-id=' + step_id +'] input[name^=actions]') , function(key , value){
debugger;
steps_actions_dates_assign[key]["action"].push(value.val());
});
});

JavaScript arrays are designed for numeric indexes and hold ordered data.
Use objects to store properties with arbitrary names.
var p = {};
p["abcd"] = "James";
In JS, an array is a kind of object so it is possible to store arbitrary properties on it, but you will run into problems when you attempt to iterate over the array or pass it to functions such as JSON.stringify.
If you are using ES6 than Maps are another option.

Related

Dynamically create a TW object in IBM BPM

I am using IBM BPM 8.6
I have an input string as follows:
"\"RECORD_CONTACT\":\"Maram\" , \"DRUG\":\"Panadol\"
In a script on server side, I want to dynamically create a business object like this:
tw.local.recordContact = Maram;
tw.local.drug = Panadol;
How can I dynamically create the business object?
There are a few problems with your request. The first is that you are not creating a business object, you are creating variables. In IBM BPM the variables have to be declared at design time or you will get an error, so invoking attempting to call something like -
tw.local.myVariable = 'Bob';
Will throw an exception if tw.local.myVariable has not been declared. Base on your other question you asked here (link), I'm going to assume you actually have an ANY variable declared called "return" so that
tw.local.return.myVariable = 'Bob'
will work. Given that I based on Sven's answer I think something like the following will work (you will need to validate)
var str = "\"RECORD_CONTACT\":\"Maram\" , \"DRUG\":\"Panadol\"";
var jsonStr = "{" + str.replace(/\\\"/g,'\"') + "}";
var tempValue = JSON.parse(jsonStr);
var keyArray = Object.keys(tempValue);
var valueArray = Object.values(tempValue);
for(var keyCount=0; keyCount<keyArray.length; keyCount++{
var evalString = "tw.local.return."+keyArray[keyCount]+"="+valueArray[keyCount];
eval(evalString);
}
I'll note that doing this is a very bad idea as it would be very brittle code and that using eval() in this manner opens you up to all sorts of possible exploits. It will also fail badly if the value for one of the keys is not a simple type.
-Andrew Paier
One should know what you are going to do with dynamically created Business Objects (BO) to answer you better. Like a very generic way would be - creating JSON object instead of BO.
But if you want to stick with BO then this is only possible when you know all the BO structure (schema) beforehand during design time.
var str = "\"RECORD_CONTACT\":\"Maram\" , \"DRUG\":\"Panadol\"";
vat objArray = str.split("reg ex to split each object string")
foreach (obj in objArray ){
if(obj.indexOf( "RECORD_CONTACT")!=-1)
tw.local.recordContact = new tw.object.RECORD_CONTACT();
//below goes code get value of each attribute of BPM from string
}
else if(obj.indexOf( "DRUG")!=-1){
//similar code to create BO DRUG
}
Don't forget to create BO before using those :)

Trying to get the"name" of a javascript object supplied by an API

I am calling an API which is giving me back, among other things, an array of javascript objects. The objects in the array are named and I need to use the name in the new individual objects I am creating from the array. Problem is, I don't know how to get to the object's name.
{
"OldCrowMine.E9001":{"last_share":1524883404,"score":"0.0","alive":false,"shares":0,"hashrate":0},
"OldCrowMine.S9001":{"last_share":1524,"score":"648.24","alive":true,"shares":632,"hashrate":14317274},
}
I am after the "OldCrowMine.E9001" bit. I am sure this is quite simple, I just don't know how to search for the answer because I am not sure what to call this. I have tried searching for a solution.
Just loop - or am I missing something? Simplified raw data version.
var raw = {
"OldCrowMine.E9001":{"share":1524883404},
"OldCrowMine.S9001":{"share":1524}
};
for(var first in raw) {
console.log(first +" share -> "+ raw[first]["share"]);
}
var obj = {
"OldCrowMine.E9001":{"last_share":1524883404,"score":"0.0","alive":false,"shares":0,"hashrate":0},
"OldCrowMine.S9001":{"last_share":1524,"score":"648.24","alive":true,"shares":632,"hashrate":14317274},
}
console.log(Object.keys(obj)[0]);
Get the keys and map the name and the object:
var x= {
"OldCrowMine.E9001":{"last_share":1524883404,"score":"0.0","alive":false,"shares":0,"hashrate":0},
"OldCrowMine.S9001":{"last_share":1524,"score":"648.24","alive":true,"shares":632,"hashrate":14317274},
};
var mapped = Object.keys(x).map(function(d,i){return [d,x[d]]});
The name is map[n][0] and its object is map[n][1] where n is your item number.

Shift is not a function in javascript

I have multiple tables(with same structure)in my html. They are in tabs. I am creating tabs dynamically and i want to send those table data to the mysql database. So i wanted to get those data using javascript. I am correctly created TableData1,TableData2.... arrays using for loop. Problem is I cannot increment TableData here ('TableData'+i).shift(); . I am getting an error. I want to create TableData1.shift(),TableData2.shift().....
function myDataSendFunction(){
var i;
for(i = 1; i <= array_size; i++){
eval("var TableData"+i+"=[];");
$('#mytable'+i+ ' tr').each(function(row, tr){
('TableData'+i)[row]={
"colum1" : $(tr).find('td:eq(1)').text()
, "colum2" :$(tr).find('td:eq(2)').text()
, "colum3" : $(tr).find('td:eq(3)').text()
, "colum4" : $(tr).find('td:eq(4)').text()
, "colum5" : $(tr).find('td:eq(5)').text()
, "colum6" : $(tr).find('td:eq(6)').text()
, "colum7" : $(tr).find('td:eq(7)').text()
, "colum8" : $(tr).find('td:eq(8)').text()
}
});
('TableData'+i).shift();
}
}
I am getting this error.
Uncaught TypeError: ("TableData" + i).shift is not a function
at myDataSendFunction (<anonymous>:25:25)
at HTMLInputElement.onclick (create.php:1)
It's clear that you are very new to this, so I'm going to show you first and then explain second.
function myDataSendFunction(){
var i,
TableData = [];
for(i = 1; i <= array_size; i++){
TableData[i] = [];
$('#mytable' + i + ' tr').each(function(row, tr){
TableData[i][row]={
"colum1" : $(tr).find('td:eq(1)').text()
, "colum2" : $(tr).find('td:eq(2)').text()
, "colum3" : $(tr).find('td:eq(3)').text()
, "colum4" : $(tr).find('td:eq(4)').text()
, "colum5" : $(tr).find('td:eq(5)').text()
, "colum6" : $(tr).find('td:eq(6)').text()
, "colum7" : $(tr).find('td:eq(7)').text()
, "colum8" : $(tr).find('td:eq(8)').text()
};
});
TableData[i].shift();
}
}
Base on your comment:
what should i do then?? I tried with TableData array, then problem occurs in here TableData[i][row] with Uncaught TypeError: Cannot set property '0' of undefined
Your troubles revolve around setting properties on variables that haven't been defined. You must define TableData before attempting to assign a property.
Once TableData is "initialized" to an array (var TableData = []), you can set properties on TableData. But you cannot immediately set properties on properties of TableData. For example, you cannot jump directly to TableData[i][row]. You must first set TableData[i] to an array (TableData[i] = []), and then you can set TableData[i][row] to some value.
By trying to solve that problem with eval, you ran into a whole new world of problems. Try to avoid eval... it's a very complicated beast that tends to cause a lot of confusion and pain.
It may be helpful to review MDN's Working with objects documentation to better understand what's going on with JavaScript's array and objects.
Apparently your element selection is the mistake you have done. Without using a for loop by hard coding an array_size you could have easily
select all the tables at once using a common property like class. You will get an array with table objects.
Iterate the table objects array.
Inside the loop select all the rows of each table and put them into another loop to extract data and create the data array which you sends to the DB.
Find my sample implementation here.
Please do remember that when you're planning to use arrays, stick to the arrays rather than moving back and forth between strings and arrays. It will cause you problems like what you have already came across and unnecessary dirty code.

JS: encapsulated foreach loop with arrays for JSON

I'm trying to get a foreach loop in a second one.
My code:
var results = data.d.results;
var boxes= [
"Nmb1",
"Nmb2",
"Nmb3",
"Nmb4",
"Nmb5",
];
boxes.forEach(function(n){
var boxesEach = results[0].n.results;
boxesEach.forEach(function(i){
$("input[value="+'"'+i+'"'+"]").attr('checked', true);
});
});
What I'm trying to do is to make for example "Nmb1" replacing the "n" which would make the following "output code":
var boxesEach = results[0].Nmb1.results;
It works if I just put the code like that but not with the loop.
Thanks for help and tips.
BTW: I'm getting the JSON via AJAX from a Sharepoint 2013 server (with the REST API).
You need to use it like an index. This is called the bracket notation (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Bracket_notation)
var boxesEach = results[0][n].results;
The one you have right now tries to use a Dot notation for which you'd need the actual property name (i.e. Nmb1) and not a variable which holds the property name.

Array displays zero length and no value with each()

I am more familiar with PHP than with JQuery and kind of stuck on arrays. I have read just about all the posts on the forum on this subject but can't get it to work.
I have what I believe to be an array.
Something that would look like this in php
myArr = ['option-4' => '3','option-1' => '8', 'option-3' => '0' ];
In JQuery I can retrieve the values by use of the command
var x = myArr['option-1'];
This all works fine but what I need to do is make a string of the values. So I need to loop through the elements and add the value of the element to the string. The problem is the loop.
When I check the length of the array
alert("Elements in array "+myArr.length);
it always returns zero.
When I try something like
$.each(myArr , function(i, val) {
alert(myArr[i]);
});
Nothing shows.
I am missing something obviously, my PHP knowledge must be blocking things.
Can anyone please help?
That is not a valid JavaScript array. You want to use an object:
var myArr = {'option-4': '3', 'option-1': '8', 'option-3': '0' };
You can then iterate over all keys using a for .. in:
for (var key in myArr) {
alert(myArr[key]);
}
This is equivalent to a associative array in PHP. Note that you need to use the explicit key to access an element, you cannot use an index, eg myArr[0].
If you want to use jQuery:
$.each(myArr , function(key, val) {
alert(key + ": " + val);
});

Categories