我有一个getter从cookie中获取值。
现在我有了两个cookie,名字分别是shares=和obligation =。
我想让这个getter只从义务cookie中获取值。
我怎么做呢?因此for语句将数据拆分为单独的值,并将其放入数组中。
function getCookie1() {
// What do I have to add here to look only in the "obligations=" cookie?
// Because now it searches all the cookies.
var elements = document.cookie.split('=');
var obligations= elements[1].split('%');
for (var i = 0; i < obligations.length - 1; i++) {
var tmp = obligations[i].split('$');
addProduct1(tmp[0], tmp[1], tmp[2], tmp[3]);
}
}
const cookies = 'key1=chocolate; key2=iceCream; key3=cookies;';
// convert string into array with split
const arrCookies = cookies.split('; '); // [ 'key1=chocolate', 'key2=iceCream', 'key3=cookies' ]
// split key value by equal sign
const arrArrCookiesKeyValue = arrCookies.map(cookie => [cookie.split('=')]); // [[['key1', 'chocolate']], ...']
// make an object with key value
const objectKeyValueCookies = {}; // { key1: 'chocolate', key2: 'iceCream', key3: 'cookies;' }
for (let arr of arrArrCookiesKeyValue) {
objectKeyValueCookies[arr[0][0]] = arr[0][1];
}
// find the key in object
const findValueByKey = (key = null, objectCookies) => objectCookies[key];
console.log(findValueByKey('key2', objectKeyValueCookies)); // chocolate