[英]Convert string into key-value pair array
I am reading checkbox name and value. 我正在读取复选框的名称和值。 If there are two checkboxes if part gets executed, if single checkboox then else block will get execute.
如果零件被执行,则有两个复选框;如果单个checkboox,则else块将被执行。
if (Array.isArray(b.name)) {
b.options = b.name.map(function(v, i) {
return [v, b.value[i]];
});
} else {
b.options = b.name.map(function(v, i) {
return [v, b.value[i]];
});
}
In the above code if block will get executed only when there are multiple value and it works fine because we have an Array. 在上面的代码中,if块仅在存在多个值时才会执行,并且因为我们有一个Array,所以可以正常工作。
name = Spine
and value = Spine Value
But in below scenario: name = Spine
和value = Spine Value
但在以下情况下:
Here else part will get execute from the above snippet. 在这里,其他部分将从上述代码片段执行。 But here it is returning an error saying that
b.name.map is not a function
. 但是这里返回了一个错误,说
b.name.map is not a function
。
How do I convert this string into an array similar to if block. 如何将此字符串转换为类似于if块的数组。
Tried approached so far in else block: 到目前为止,在else块中尝试过:
b.options = $.each(function(v, i) {
return [b.name, b.value];
});
$.each({name: b.name, value: b.value}, function(k, v) {
b.options = (k + "" + v);
});
if b.name has length attribute,you can use 'call' 如果b.name具有length属性,则可以使用'call'
if(Array.isArray(b.name)){
b.options = Array.prototype.map.call(b.name,function(v,i) {
return [v, b.value[i]];
})
}else{
b.options = Array.prototype.map.call(b.name,function(v,i) {
return [v, b.value[i]];
})
}
You can combine both cases by concatenating your b.name
value with an empty array: 您可以通过将
b.name
值与一个空数组串联来合并这两种情况:
b.options = [].concat(b.name).map(function(v,i) {
return [v, b.value[i]];
});
in that way, you will get an array from b.name
when is a string and also when it is an array already. 这样,当既是字符串又是数组时,您将从
b.name
获取数组。 You may need to handle the case when b
or b.name
is undefined
though. 但是,当
b
或b.name
undefined
时,您可能需要处理这种情况。 Or you can use more general zip function: 或者您可以使用更通用的zip功能:
var zip = function(arr1, arr2) {
var a = [].concat(arr1);
var b = [].concat(arr2);
var len = Math.min(a.length, b.length)
return a.slice(0, len).map(function(item, i){
return [a[i], b[i]];
});
}
b.options = zip(b.name, b.value);
Mind in that case that the returned array will have the length of the shortest array. 请注意,在这种情况下,返回的数组将具有最短数组的长度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.