Home > Blockchain >  Write a cookie string from a array of cookies in the same order regardless the position of the cooki
Write a cookie string from a array of cookies in the same order regardless the position of the cooki

Time:11-10

I have an array of cookies like this:

const cookie = [
  '__uzma=e6954f29-7e77-4beb-a278-5fd2b628763d; HttpOnly; path=/; Expires=Thu, 05-May-22 17:41:57 GMT; Max-Age=15724800',
  '__uzmb=1636047717; HttpOnly; path=/; Expires=Thu, 05-May-22 17:41:57 GMT; Max-Age=15724800',
  '__uzmc=767031033660; HttpOnly; path=/; Expires=Thu, 05-May-22 17:41:57 GMT; Max-Age=15724800',
  '__uzmd=1636047717; HttpOnly; path=/; Expires=Thu, 05-May-22 17:41:57 GMT; Max-Age=15724800',
  'JSESSIONID="7kibk5hbeCNhPyQscS9ZKcZn.nodelx219:mobnbcinter01p-lx219"; Version=1; Path=/sinbc; Secure',
  'bJ1spGC0yyDM=v1TQPygxWcMCu; Expires=Thu, 04-Nov-2021 17:56:57 GMT; Path=/'
]

and i need to write a string of cookie like this, always with the same order of keys.

JSESSIONID="FD7nr80tcgNz0B7nVB pjClV.nodelx128:mobnbcinter06e-lx128"; __uzma=74752190-a1e1-4570-ba81-74cf7375a967; __uzmb=1636049499; __uzmc=401341072218; __uzmd=1636049499; bJ1spGC0yyDM=v1HQPygxKcahm

The order is always JSESSION, uzma, uzmb, uzmc, uzmd, bJ1spGC0yyDM

const keyOrder = [
  'JSESSIONID',
  '__uzma',
  '__uzmb',
  '__uzmc',
  '__uzmd',
  'bJ1spGC0yyDM'
]

Which is the best way to do this? map startsWith? How can I do?

CodePudding user response:

You have 3 options to solve it:

const result = cookie.map((c, index) => c.split(';')[0]).sort((a, b) => {
    return keyOrder.indexOf(a.split('=')[0]) - keyOrder.indexOf(b.split('=')[0]);
}).join(';');
console.log(result);

OR

let result = '';
for (i = 0; i < keyOrder.length; i  ) {
    var filteredItem = cookie.filter(x => x.startsWith(keyOrder[i]))[0];
    result = `${result}${keyOrder[i]}=${filteredItem.split('=')[1].split(';')[0]};`;
}
console.log(result);

OR

var output = {};
cookie.forEach(function (item, index) {
    let key = item.split(";")[0].split("=")[0];
    let value = item.split(";")[0].split("=")[1];
    output[key] = value;
});

result = ""
keyOrder.forEach(function (item, index) {
    result  = `${item}=${output[item]};`
});
console.log(result);
  • Related