-4

I have a string in my jquery variable like this

var str = {"xid":"ICAQ2OWE4MjcwYTY=","eci":"05","cavv":"BwABBUCxSrHAA=","status":"A"}

How can I convert it into an array to get the values separately? I want to get values like

var xid = "ICAQ2OWE4MjcwYTY=";
var eci = "05";
var cavv = "BwABBUCxSrHAA=";
var status = "A";
georg
  • 211,518
  • 52
  • 313
  • 390
Yunus Aslam
  • 2,447
  • 4
  • 25
  • 39

3 Answers3

4

You could take a destructuring assignment for the properties as variables, which works in any scope.

var object = { xid: "ICAQ2OWE4MjcwYTY=", eci:"05", cavv:"BwABBUCxSrHAA=", status:"A" },
    { xid, eci, cavv, status } = object;

console.log(xid);
console.log(eci);
console.log(cavv);
console.log(status);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 1
    But that requires you to know each variable name. – Zenoo Feb 09 '18 at 09:38
  • 1
    @Zenoo If you don't know the property names, then you should not create the variables in the first place but just keep them in the object. – str Feb 09 '18 at 09:38
  • 1
    @str Well, if you already know the property names, I don't really see a point in asking the question in the first place. – Zenoo Feb 09 '18 at 09:43
  • 1
    @Zenoo Me neither. But *not* knowing the properties and creating local variables makes even less sense. – str Feb 09 '18 at 09:45
  • This is a bit too much for Friday morning :) – Andy Feb 09 '18 at 09:49
3

You can easily use dot notation to access values associated with a key in an object.

var str = {"xid":"ICAQ2OWE4MjcwYTY=","eci":"05","cavv":"BwABBUCxSrHAA=","status":"A"}

var xid = str.xid;
console.log(xid);
void
  • 36,090
  • 8
  • 62
  • 107
2

You can loop over your object with a for and populate the window object with window[key] = str[key]:

var str = {"xid":"ICAQ2OWE4MjcwYTY=","eci":"05","cavv":"BwABBUCxSrHAA=","status":"A"}

for(var key in str){
  window[key] = str[key];
}

console.log(xid);
console.log(eci);
console.log(cavv);
console.log(status);
Zenoo
  • 12,670
  • 4
  • 45
  • 69
  • You should not use `window[key]` as that creates the variables in the *global* scope. – str Feb 09 '18 at 09:37
  • @str which is exactly what the OP wanted. – Zenoo Feb 09 '18 at 09:38
  • No, the OP did not specify that he wants them to be in the global scope. For example, if you use your code inside of a function, it will create the variables outside (i.e. global) of the function. – str Feb 09 '18 at 09:40