correct a malformed javascript array - javascript

I send a php array like:
$var = array (
0=> 4,
1=> 6,
2=> 8,
...
as json_encode($var); into the uri and then I receive it into javascript file is still ok here but when I push it into new array like this :
this.patg.push(attd);
Is inserted like this below .
var attds = ["4,6,7,8,9,5558,5560,5573,5574,5586,5589,5606"]
I know I have to find the problem. but
Questions:
could you please tell me why this could happends or help me to deal with it.
but in any case just for knowledge . how you would add the extra " " surrounding the , that i miss to be an array , or is that crazy idea to fix this?

If you are receiving a string value and you want to use it as an array of integers you should split it into an array first:
var receivedData = "4,6,7,8,9,5558,5560,5573,5574,5586,5589,5606";
var dataArray = receivedData.split(",");
Afterwards you can use it with another array, however be aware that if you already have a defined array into which you want to push the dataArray you shouldn't push but concat instead.
In other words if you have:
var previousArray = [1,2,3];
previousArray.push(dataArray);
You will get
[1,2,3,[4,6,7,8,9,5558,5560,5573,5574,5586,5589,5606]]
meaning that the whole array is pushed onto the 4th position of previousArray.
If, on the other hand, you concat the arrays will merge:
var previousArray = [1,2,3];
previousArray.concat(dataArray);
[1,2,3,4,6,7,8,9,5558,5560,5573,5574,5586,5589,5606]
Source: http://www.w3schools.com/jsref/jsref_concat_array.asp

Related

JS How can I convert a serialized object to an Array?

Using jquery.nestable.min.js, I get a the following output:
[{"id":32},{"id":29},{"id":30}]
This current output is coming from the following code:
const myList = JSON.stringify(list.nestable('serialize'));
I need it to simply be:
32, 29, 30
End result is that I would like to read a normal array in PHP. I'm looking to either convert myList to an array in Javascript and POST that array, or convert the current version of the object to an array inside PHP, whichever is most effective.
I've tried to use json_decode in PHP, but I get empty values. So I figured if I can just convert to a normal Array before sending it off to PHP, then it would be less of a hassle.
Thank you.
This may be duplicated, in which case, please point me to the best answer
Depending on whether you want an array (per your title), or literally 32, 29, 30 per your post:
console.log([{"id":32},{"id":29},{"id":30}].map(i => i.id))
console.log([{"id":32},{"id":29},{"id":30}].map(i => i.id).join(', '))
Which, with your example, is probably going to be:
const myList = JSON.stringify(list.nestable('serialize').map(i => i.id));
If you just want an array of numbers, convert that output array of objects to array of numbers
var list = [{"id":32}, {"id":29}, {"id":30}];
var required = list.map(item => item.id);
console.log(required);

Get a key from an array inside an array in javascript

var Game1 = ["name", "image", "genre"]
var Game2 = ["name2", "image2", "genre2"]
var Game3 = ["name3", "image3", "genre3"]
var games = [Game1, Game2, Game3]
I want to store some arrays inside an other array, as shown above, and I want to be able to show all of the names of the arrays. So here, I would like to get Game1[0], Game2[0] and Game3[0], but I want to get them from the games array.
How would I go about doing this?
I was thinking of using a for loop over games, but I'm not sure how to get the 0th element from the arrays inside the games array.
I'm quite new to javascript, which is why I could not figure this out.
You can access like below.
games[0][0] - will gives you the Game1[0] value
games[1][0] - will gives you the Game2[0] value
games[2][0] - will gives you the Game3[0] value
DEMO

Organise array push order

I've got an array. I push items multiple times into this array using a function. Below is an simplified version of the code.
var arr = [];
function pushItems(i){
//do something with i
var abc = "string"
arr.push(abc);
//do something with i
var xyz = "string"
arr.push(xyz);
}
Sometimes abc value is pushed before xyz. Sometimes xyz gets pushed before abc value. My question is how do I always have the abc value ahead of 'xyz' value?
So basically I need the array values to be [abc1, xyz1, abc2, xyz2, abc3, xyz3, ...] so on. How do I order the push accordingly?
This is wrong. According to the specification of this method:
The push() method adds one or more elements to the end of an array and
returns the new length of the array.
Please have a look here.
For a more formal approach please see the ECMAScript specification here.
The arguments are appended to the end of the array, in the order in
which they appear. The new length of the array is returned as the
result of the call.
Update
But even if the elements are added at the end of the array, I'm
looking a way of ordering my array.
You can use the sort function for this reason passing to it an appropriate function that will do the compare. For instance, let we have the following array
var array = [4,1,2,5,3];
and we want to order it in a descending order, we could do this like below:
var array = array.sort(function(a,b){ return b-a; });
Since you need your base64-strings to be in an arbitrary order in the array, sort them by an identifier you define.
var firstObj = {id: 0, base64: 'asdf'}
var secondObj = {id: 1, base64: 'qwer'}
var arr = []
// do stuff
// callback needs to have something along these lines:
function base64isLoaded(obj){
arr[obj.id] = obj.base64;
}
Now the 'front' image (as you gave this as example) can be given id: 0, so it ends up in the '0' spot of the array. I can't really help more without more information about how your code is structured.
EDIT: From your comment ("passing multiple items into pushItems"), I am going to assume that i (the argument) is an array and you iterate this array to transform each element into a base64 encoded string. You then want these encoded strings added to arr in the same order, correct?
easily done, simply make i an array of objects:
var i = [{source: 'abc'}, {source: 'xyz'}];
pushItems(i){
for(var c = 0; c < i.length; c++){
makeIntoBase64(i[c]);
}
}
makeIntoBase64(obj){
// this is whatever function that transforms it and takes a callback when it is done
transform(obj.source, function(result){ //pass the source to be encoded
//result should be base64 encoded string
obj.encoded = result;
});
}
after all this, the array i has objects with both .source and .encoded. If you need to know when ALL encoding is done, create a counter and add one to it in the transform callback, and check if counter === i.length every time. When it is, you know you have loaded all base64 strings and can run another function, adding these images to your catalogue or whatever else you need this for :)

How can I push a null value into the start of an array?

I have this code that fetches data and puts it into an array:
this.$httpGetTest(this.test.testId)
.success(function (data: ITestQuestion[]) {
self.test.qs = data;
});
It works and populates the array starting with self.test.qs[0].
However many times my code references this array (which contains a list of questions 1...x)
I must always remember to subract 1 from the question number and so my code does not look clear. Is there a way that I could place an entry ahead of all the others in the array so that:
self.test.qs[0] is null
self.test.qs[1] references the first real data for question number 1.
Ideally I would like to do this by putting something after the self.test.qs = and before data.
Push values at start of array via unshift
self.test.qs.unshift(null);
You need to use Splice(), It works like:
The splice() method changes the content of an array, adding new elements while removing old elements.
so try:
self.test.qs.splice(0, 0, null);
Here mid argument 0 is to set no elements to remove from array so it will insert null at zero and move all other elements.
Here is demo:
var arr = [];
arr[0] = "Hello";
arr[1] = "Friend";
alert(arr.join());
arr.splice(1,0,"my");
alert(arr.join());
You can start off with an array with a null value in it, then concat the questions array to it.
var arr = [null];
arr = arr.concat(data);
You could do something like:
x = [null].concat([1, 2, 3]);
Though there isn't anything wrong with doing something like:
x[index-1]
I'd prefer it to be honest, otherwise someone might assume that the index value returned is 0 based.

Storing values in array and retrieving from array when checkbox is checked

I am storing some values in array like this.
var test = [];
I am pushing the values to this array as test.push(sample);
I have some logic for calculating this value
var sample= (a/b.length)*100;
When I click on a button, the above logic for calculating value of sample is done and once I got the value of sample I am pushing it to test[] array. Now I want to retrieve all the values from the test[] array whenever I check the checkbox. I am able to do all this but I am facing a problem here. only the last pushed value is saving. but I want to save all the values that are being pushed. can anyone please help me in solving this issue.
Quick response is needed and appreciated
Regards
Hema
You need to use 2 dimensional array for this.
Use
var test= new Array();
then assign value test['someKey']=sample;
or test.push(sample); . you can retrieve array value like alert(test[0]) or by iterating array with $.each(test,function(index,value){alert(value)});
What you want to do is create an Array which would function as a list of value sets.
You would then be able to push all the changes into an array, and put it in the list.
for instance:
var mainList = new Array();
var changeListA = new Array();
var changeListB = new Array();
// do some stuff on change list **a** .. push(something)
changeListA .push(something);
changeListA .push(something);
changeListA .push(something);
// do some stuff on change list **b** .. push(something)
changeListB .push(changeListB);
mainList.push(changeListA);
Your question is not perfectly clear to me, however I can at least provide a small jsFiddle that proves to you that (how) array.push works.
Other answers indicate that what you want is either a two dimensional array, or a "hashmap" or "associative array" where the array values are stored using a key name. The code here can be used in the fiddle to achieve either or...
http://jsfiddle.net/xN3uL/1/
// First if you need 2 dimensional arrays:
myArray.push( ["Orange", "Apple"] );
myArray.push( ["Mango", "Pineapple"] );
// Secondly, if you need hashmap or associative array:
var myObj = {};
myObj['key'] = 'value';
alert(myObject.key);

Categories