Home Ask Login Register

Developers Planet

Your answer is one click away!

sajalsuraj February 2016

Why an object key's first value is treated as a string - AngularJs

I have an object named as "param" and it has a key named as "item[]". The values of item[] are inserted dynamically.

Problem is when "item[]" has a single value, it treats that value as a string and not as first index of array.

Example :


but when it has multiple values then it treats itself as an array which is desired, example-

item[] = ["123","456"];

I want the single value also as index of this array like

item[] = ["123"]

How would I do it ?

P.S. - This object is created from querystring parameters like http://example.com/def?item[]=123&item[]=456, then when I extract querystring, it returns these parameters as the keys of an object

I am extracting querystring in this way(Javascript)-

var param = $location.search();
console.log(param);//Returns Object{item[]=[2]} in console


Mahantesh Kumbar February 2016

Try this

queryString = ["123"];
queryString = ["123","432","456"];
       item.push(value);//push only value

gr3g February 2016

This is because variableName[] is not a javascript syntax.
Since it does not recognise the [], it is probably part of the name if it does not throw an error.

To create an array, you have 2 possibilities :

var ar = new Array(); //empty array
var ar = []; //same as above
var ar = [0,1,2,3]; //array of length 4
var ar = new Array(4); //empty array of length 4

to access or set it

var ar[0] = "value"

sajalsuraj February 2016

I have solved it -

if(typeof param['item[]'] == "string"){
    param['item[]'] = [param['item[]']];

First I am checking if the key has a string value, if it is string then I am converting it into an array and it worked.

Here is the working fiddle -


Post Status

Asked in February 2016
Viewed 1,947 times
Voted 12
Answered 3 times


Leave an answer

Quote of the day: live life