我编写了以下代码,它接受一个数组并将其转换为过滤器字符串,生成该字符串,但不是
product_size=123&product_size=456
我希望它是product_size=123+456
。
我怀疑我需要检查product_size的数组键是否已经存在,然后将第二个数字插入其中,然后生成过滤字符串。
我已经创建了一个 keysAlreadyUsed
数组,但我不知道如何执行此操作。
也许我想得太多了,某种形式的字符串操作就足够了。
// Array
arrayTest = [];
arrayTest.push( ['product_size', 123] );
arrayTest.push( ['product_size', 456] );
arrayTest.push( ['product_color', 123] );
// Start filter string and array of keys already used
filterString = '';
keysAlreadyUsed = [];
// Loop the array test
$.each( arrayTest, function( index1, value1 ) {
// If the key has already been set
if( jQuery.inArray( value1[0], keysAlreadyUsed ) ) {
// Push into the existing array key
} else {
// New array we can loop through later with the product_size and the 123, 456 in it.
}
// Populate filter string
filterString += value1[0] + '=' + value1[1] + '&';
// Push the key already used into the keys already used array
keysAlreadyUsed.push( value1[0] );
});
// Output
console.log(filterString);
console.log(keysAlreadyUsed);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
jsFiddle: https://jsfiddle.net/6oxc8umz/2/
最佳答案
也许不是最有效的。
第一次调用函数reduce
用于创建key-value
对象,第二次调用用于生成queryString。
let arrayTest = [['product_size', 123], ['product_size', 456] ,['product_color', 123]],
result = Object.entries(arrayTest.reduce((a, [key, value]) => {
if (a[key]) a[key] += `+${String(value)}`;
else a[key] = value;
return a;
}, Object.create(null))).reduce((a, [key, value]) => a + `${key}=${value}&`, "").slice(0, -1);
console.log(result);
关于javascript - 从 jQuery 数组生成查询字符串,其中查询变量有多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56794124/