[英]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[]". 我有一个名为“ param”的对象,它有一个名为“ item []”的键。 The values of item[] are inserted dynamically. item []的值是动态插入的。
Problem is when "item[]" has a single value, it treats that value as a string and not as first index of array. 问题是,当“ item []”具有单个值时,它将该值视为字符串而不是数组的第一个索引。
Example : 范例:
item[]="123";
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 ? 我该怎么办?
PS - 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 PS-此对象是通过诸如http://example.com/def?item[]=123&item[]=456之类的查询字符串参数创建的,然后当我提取查询字符串时,它将这些参数作为对象的键返回
I am extracting querystring in this way(Javascript)- 我正在以这种方式提取查询字符串(Javascript)-
var param = $location.search();
console.log('Param');
console.log(param);//Returns Object{item[]=[2]} in console
This is because variableName[]
is not a javascript syntax. 这是因为variableName[]
不是JavaScript语法。
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 : 要创建数组,您有两种可能:
//Contsructor
var ar = new Array(); //empty array
//Literal
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"
Try this 尝试这个
queryString = ["123"];
queryString = ["123","432","456"];
if(queryString.length==1){
item.push(queryString[0]);
}else{
angular.forEach(queryString,function(value,key){
item.push(value);//push only value
})
}
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 - 这是工作中的小提琴-
https://jsfiddle.net/r3vrxzup/ https://jsfiddle.net/r3vrxzup/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.