Is there a way to assign values in a JavaScript array in the way I do it in PHP.
For example in PHP I can do that:
$ar = array();
$ar[] = "Some value";
$ar[] = "Another value";
Is that posible to be done with JavaScript? Or if not is there any similar way ?
The direct translation of your original code is
var ar = [];
ar[ar.length] = "Some value";
ar[ar.length] = "Another value";
However a better looking solution is to use the pretty universal push method:
var ar = [];
ar.push("Some value");
ar.push("Another value");
As with most languages, JavaScript has an implementation of push to add an item to the end of an array.
var ar = [];
ar.push("Some value");
ar.push("Another value");
var myArray = [];
myArray.push('value1');
myArray.push('value1');
Or
var myArray = [];
myArray[myArray.length] = 'value0';
myArray[myArray.length] = 'value1';
myArray[myArray.length] = 'value2';
Check out this reference document for more about javascript arrays: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array
Arrays are treated slightly different in javascript. In PHP, an array like this:
PHP
$myArray = array();
$myArray[1] = 'value';
$myArray[10] = 'value';
echo count($myArray); // output: 2
Javascript:
var myArray = [];
myArray[1] = 'value';
myArray[10] = 'value';
console.log(myArray.length); // output: 11
What's going on here? In PHP, an array is an dynamic container. The indexes needn't be sequential - indeed, there is little difference between an associative array (an array with string indexes instead of numeric ones) and a standard array.
In javascript, the concept of "associative array" does not exists in the array context - these would be object literals instead ({}). The array object in javascript is sequential. If you have an index 10, you must also have the indexes before 10; 9,8,7, etc. Any value in this sequential list that is not explicitly assigned a value will be filled with the value undefined:
From the example above:
console.log(myArray); //[undefined, "value", undefined, undefined, undefined, undefined,` undefined, undefined, undefined, undefined, "value"]
Related
I am trying to send the JavaScript array to my php, but php gets empty [].
It even shows like that in my browser. I have always sent JSON and had no problem, but now have this format.
I have this example that makes no sense...it's just a code to illustrate the issue:
var blah = [];
var letters = ['a', 'b', 'c', 'd'];
for (var i = 0; i < letters.length; i++)
{
blah[letters[i]] = i;
}
Inside firebug DOM it shows as follows:
blah []
a 0
b 1
c 2
d 3
When I do
alert(blah) ------------------------------- I get empty
alert(JSON.stringify(blah)) ----- I get []
alert(blah.a) ---------------------------- I get 0
So how can I pass this object to php? Thanks
Instead of an array, try using an object.
So instead of:
var blah = [];
Try
var blah = {};
Arrays are continuously numerically indexed. They do not have strings as key names.
What you want is an object {}, not an array [].
Can not assign key value collection in array. You need to work on objects:
var obj = {
key1: value1,
key2: value2
};
for converting array to string you can use:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.toString();
with seperator:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.join(" and ");
Here is working Demo
try this:
var blah = {};
var letters = ['a', 'b', 'c', 'd'];
for (var i = 0; i < letters.length; i++)
{
blah[letters[i]] = i;
}
alert(JSON.stringify(blah));
I have answered this before. Anyway, blah is an array, but you are not using it as array, you are using it as a hashmap. Arrays work with indexes and maps work with keys. Any object in JS can also act like a map. For e.g
var obj = new Object();
obj.a = 10;
obj["b"] = 20;
var obj2 = function(){...}
obj2.foo = 10;
obj2.bar = "baz";
Similarly, Array is also and Object and can act like a map. But when you use the array like a map, its array is not utilized to store the elements. They just act like above. So the length of an Array is 0 even though it has properties attached to it.
What you must do is use Array methods like push and pop to populate and retrieve from it.
I am having a problem of how to organize my variables in flash that are from a PHP script.Ideally i want them in an array type format so i can loop through them.Below is some code to go with.
function completeHandler(evt:Event){ // after loading the php
var symbolsArray:Array = new Array()
symbolsArray.push(evt.target.data.symbol_1);// php variable named: symbol_1, symbol_2
trace(evt.target.data);
}
The above is allworking, the PHP variables are listed as symbol_1, symbol_2 etc
Instead of pushing each variable separably into the array i want a loop, along the lines of:
function completeHandler(evt:Event){
var symbolsArray:Array = new Array()
var counter =1
symbolsArray.push(evt.target.data.symbol_+counter); this is the issue
trace(symbolsArray[0]); //returns NaN
}
Below is the php return vars to flash to give an idea:
$returnVars['symbol_1'] = $virtualReel1[0];
$returnVars['symbol_2'] = $virtualReel1[1];
$returnVars['symbol_3'] = $virtualReel1[2];
$returnVars['symbol_4'] = $virtualReel2[0];
$returnVars['symbol_5'] = $virtualReel2[1];
//etc
$returnString = http_build_query($returnVars);
echo $returnString;
symbolsArray.push(evt.target.data["symbol_"+counter]);
If you need to dynamically query properties of an object, you address it as an Array or a Dictionary, by a string key, which can be dynamically formed. Works on anything.
The returned data can be treated as an Object (containing Objects) so you can loop thru it like so:
function completeHandler(evt:Event)
{
var symbolsArray:Array = new Array();
for each (var obj:Object in evt.target.data)
{
symbolsArray.push(obj);
}
}
If you know all items are oif same type, you can cast the object. eg: if all Numbers:
symbolsArray.push(Number(obj));
Or Strings:
symbolsArray.push(String(obj));
How to assign the value to the JSON by providing the index for it..
see the following code,
var jsonVariable = [];
jsonVariable[10] = {1:10};
alert(jsonVariable.toSource());
For the above code the output is,
[,,,,,,,,,{1:10}]
The output i expect and i need is [10 : {1:10}]
How to code to bring the output as i expect... please help me briefly..
You used index-operators ([]), which instanciate a new array and set the element at index 10 to {1: 10}. You actually wanted to use curly braces operators ({}) which instanciate a new object and ad a property 10: {1:10} like that:
var jsonVariable = {};
jsonVariable[10] = {1:10};
alert(jsonVariable.toSource());
Setting members to an array, you can't simply skip some indices (begin at 10). All uninstaciated indices until yours will forcible be created.
When you specify an array index that doesn't yet exist like [10], all previously unfilled indices are created. Just .push() it on.
var jsonVariable = [];
// A numeric property should be a string "1", though the browser will probably forgive you
// Just push the new object onto the array
jsonVariable.push({"1":10});
alert(JSON.stringify(jsonVariable));
// [{1:10}] exactly as you describe
If you need this particular object {1:10} to be present at jsonVariable[10], make it an object {} rather than an array.
var jsonVariable = {};
jsonVariable["10"] = {"1": 10};
alert(JSON.stringify(jsonVariable));
// {"10":{"1":10}}
I guess what you need is:
var jsonVariable = [];
for(var i=0;i<10;i++){
var temp = {};
temp[i] = {'Property' : "Data"}
jsonVariable.push(temp);
}
console.log( JSON.stringify(jsonVariable));
try this:
var jsonVariable = [];
jsonVariable[10] = {1:10};
function isNotEmpty(element, index, array) {
return array[index];
};
jsonVariable = jsonVariable.filter(isNotEmpty);
alert(jsonVariable.toSource());
I receive from the server a JSON like the following:
{"0":{"0":"image1.jpg","1":"texthere","2":"0"},"1":{"0":"image66.jpg","1":"texthere","2":"1"},"2":{"0":"image12.jpg","1":"texthere","2":"2"},"3":{"0":"image44.jpg","1":"texthere","2":"3"},"4":{"0":"image34.jpg","1":"texthere","2":"4"},"5":{"0":"image33.jpg","1":"texthere","2":"5"},"6":{"0":"image21.jpg","1":"texthere","2":"6"},"7":{"0":"image32.jpg","1":"texthere","2":"7"},"8":{"0":"image13.jpg","1":"texthere","2":"8"},"9":{"0":"image11.jpg","1":"texthere","2":"9"},"10":{"0":"image03.jpg","1":"texthere","2":"10"},"length":"12"}
The developer who coded this used JSON_FORCE_OBJECT as a parameter of the json_encode method in PHP.
In JavaScript is there any "magics" (that is, not a custom function) to convert this structure to a multidimensional array?
I would want something like:
[["image1.jpg","texthere","2"],["image66.jpg","texthere","1"]]...
Disclaimers:
- I'm looking for a native implementation (not JQuery);
- The PHP can be eventually changed (if needed);
Any help is appreciated, thanks in advance.
The easiest way I can think of to do what you want is to use regular expressions to convert the JSON from object literals to array literals.
Unfortunately, Simon Cowell is more magical than this approach.
//I don't know why you don't want a custom function.
function dataToArray(data)
{
data = data.replace(/"[0-9]+":/g,""); //Remove all index keys
data = data.replace(/,"length":"[0-9]+"/g,""); //Remove length key-value pair
data = data.replace(/{/g,"["); //Change the left brackets
data = data.replace(/}/g,"]"); //Change the right brackets
return JSON.parse(data);
}
Not magic, but you can loop over the data and test what type of value it has.
A basic example would be as follows. It doesn't have the error checking I'd want in production code though.
var data = {"0":{"0":"image1.jpg","1":"texthere","2":"0"},"1":{"0":"image66.jpg","1":"texthere","2":"1"},"2":{"0":"image12.jpg","1":"texthere","2":"2"},"3":{"0":"image44.jpg","1":"texthere","2":"3"},"4":{"0":"image34.jpg","1":"texthere","2":"4"},"5":{"0":"image33.jpg","1":"texthere","2":"5"},"6":{"0":"image21.jpg","1":"texthere","2":"6"},"7":{"0":"image32.jpg","1":"texthere","2":"7"},"8":{"0":"image13.jpg","1":"texthere","2":"8"},"9":{"0":"image11.jpg","1":"texthere","2":"9"},"10":{"0":"image03.jpg","1":"texthere","2":"10"},"length":"12"};
function data_to_array(data) {
var array = [];
for (var key in data) {
var value = data[key];
if (typeof value === 'string') {
array[key] = value;
} else {
array[key] = data_to_array(value);
}
}
return array;
}
var array = data_to_array(data);
console.log(array);
Make sure you add hasOwnProperty checks if your object prototypes might be messed with. You should probably also add a check to make sure that only integer keys are added to the array.
There is no built-in functions. If you have JSON string, you can do string replacement, otherwise you have to loop as shown below.
var dataObject = {"0":{"0":"image1.jpg","1":"texthere","2":"0"},"1":{"0":"image66.jpg","1":"texthere","2":"1"},"2":{"0":"image12.jpg","1":"texthere","2":"2"},"3":{"0":"image44.jpg","1":"texthere","2":"3"},"4":{"0":"image34.jpg","1":"texthere","2":"4"},"5":{"0":"image33.jpg","1":"texthere","2":"5"},"6":{"0":"image21.jpg","1":"texthere","2":"6"},"7":{"0":"image32.jpg","1":"texthere","2":"7"},"8":{"0":"image13.jpg","1":"texthere","2":"8"},"9":{"0":"image11.jpg","1":"texthere","2":"9"},"10":{"0":"image03.jpg","1":"texthere","2":"10"},"length":"12"};
function getArray(object){
var array = [];
for(var key in object){
var item = object[key];
array[parseInt(key)] = (typeof(item) == "object")?getArray(item):item;
}
return array;
}
var dataArray = getArray(dataObject);
Example output from PHP:
{
"RootName_0":{"Id":1,"ValId":1,"Value":"Colour","Text":"Blue"},
"RootName_1":{"Id":1,"ValId":2,"Value":"Colour","Text":"Red"}
}
How can I use Backbone.js or jQuery to only have:
[
{"Id":1,"ValId":1,"Value":"Colour","Text":"Blue"},
{"Id":1,"ValId":2,"Value":"Colour","Text":"Red"}
]
If it's easier to use PHP to edit the JSON, then so be it.
Well, in PHP it would be easy, just use array_values() on the initial array so that it 'forgets' the array indexes (which by the way, is what 'RootName_X' is called in your case:
$newvalue = array_values( (array)$value );
echo json_encode($newvalue);
In javascript, it's a bit trickier, but it would be on the lines of:
var newvalue = [];
for(var root in value)
newvalue.push(value[root]);
The question title is was a bit confusing since these are certainly not tags.
No need for jquery or Backbone:
var obj = {
"RootName_0":{"Id":1,"ValId":1,"Value":"Colour","Text":"Blue"},
"RootName_1":{"Id":1,"ValId":2,"Value":"Colour","Text":"Red"}
};
var colors = [];
for(var key in obj){
colors.push(obj[key]);
};
The value you want is now in the colors array.
Using ES5 (modern browsers) you could do:
Object.keys(received).map(function(key) {
return received[key];
});
Basically, converting the object into an array of its keys, then replacing each key with the value.
In javascript, if myFirstVar contains the initial object, then do:
mySecondVar = [ myFirstVar.RootName_0, myFirstVar.RootName_1 ];
Once the JSON has been parsed, do it using jQuery's jQuery.map, and borrowing the global Object function...
var arr = $.map(obj,Object);
EDIT:
If you do it in JavaScript, you should be aware that the objects may not remain in their original order.
You can remedy this if the RootName_n keys are sequential, and you know the n of the last key.
var last_key = 20;
var arr = [];
for(var i = 0; i <= last_key; i++)
arr.push( obj['RootName_' + i] );