简体   繁体   English

搜索字符串键数组以匹配变量,并使用javascript / jquery返回所有值

[英]Search array of string keys for matching variable and return all values using javascript / jquery

I am building an ecommerce application, part of which creates a cookie when the user adds products to a basket (US English: please read 'cart'). 我正在构建一个电子商务应用程序,当用户将产品添加到购物篮中时,其中一部分会创建一个cookie(美国英语:请阅读“购物车”)。 The application's logic often generates multiple baskets (and therefore multiple cookies) per user. 应用程序的逻辑通常会为每个用户生成多个篮子(因此会生成多个cookie)。 Each cookie is given a key, which always begins with the string 'basket' following by an ascending integer. 每个cookie都有一个键,该键始终以字符串“ basket”开头,后跟一个升序整数。 Each basket is given an id, which is a 32 character string, stored as the cookie's value. 每个购物篮都有一个ID(它是32个字符串),存储为cookie的值。

Within the cookies, the user's basket ids are stored as strings, each with a name / value pair. 在Cookie中,用户的购物篮ID以字符串形式存储,每个字符串都有一个名称/值对。 I have managed to push all of the cookie name / value pairs into an array, such that the array reads: 我已经设法将所有cookie名称/值对推入一个数组,以便该数组读取:

["mcart=537244a1377f97374fff2233cdc29bdf", " mtoken=0f9a74b73d2f29b1c6088d63b7f4f4a5c545bbe9", " mexpires=1468626166000", " basket1=aw7j0r9ke3hq8tp20egf7105dozfn13i", " basket2=kpxpdnw6nnfyvawmk7n4s7pd9meaimy7", " basket3=9264k594wi9vgfiotkvz323n35yfvkkf"]

I have created a variable: 我创建了一个变量:

var name = 'basket';

My aim is to use javascript (presumably regex), or indeed jquery, to: 我的目标是使用javascript(大概是regex)或jquery来:

  • return the values for the key/value pairs with keys matching 'basket1', 'basket2' and 'basket3' (please note the extra space in the keys which directly follows the opening quotation marks); 返回键/值对具有与“ basket1”,“ basket2”和“ basket3”匹配的键的值(请注意,键中紧跟在引号后面的多余空间);
  • continue to match and return values for future key/value pairs created (eg 'basket4', 'basket5', 'basket91'); 继续匹配并返回创建的将来键/值对的值(例如“ basket4”,“ basket5”,“ basket91”);
    • return said values in an javascript array. 在javascript数组中返回所述值。

THANK YOU in advance to the community. 预先感谢社区。

var cookies = ["mcart=537244a1377f97374fff2233cdc29bdf", " mtoken=0f9a74b73d2f29b1c6088d63b7f4f4a5c545bbe9", " mexpires=1468626166000", " basket1=aw7j0r9ke3hq8tp20egf7105dozfn13i", " basket2=kpxpdnw6nnfyvawmk7n4s7pd9meaimy7", " basket3=9264k594wi9vgfiotkvz323n35yfvkkf"];

var baskets = [];

for (var i = 0; i < cookies.length; i++) {
    var match = cookies[i].match(/basket\d+=(.*)/);
    if (match) {
        baskets.push(match[1]);
    }
}

console.log(baskets);

// Output:
// [ 'aw7j0r9ke3hq8tp20egf7105dozfn13i',
//   'kpxpdnw6nnfyvawmk7n4s7pd9meaimy7',
//   '9264k594wi9vgfiotkvz323n35yfvkkf' ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM