Javascript Data Type How to - Separate key value pairs into two variables with for loop








Question

We would like to know how to separate key value pairs into two variables with for loop.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--   w  ww .j a  v a 2 s . c  o  m-->
var user_input="example";
var array=["foo:bar","baz:example","cat:dog"];
    var pair,obj1={},obj2={};
    for (var i=0;i<array.length;i++) {
      pair=array[i].split(":");
      obj1[pair[0]]=pair[1];
      obj2[pair[1]]=pair[0];
    }
    
    if (obj1[user_input]) {
       document.writeln([user_input,obj1[user_input]]);
    } else if (obj2[user_input]) {
       document.writeln([obj2[user_input],user_input]);
    }
    else {
       document.writeln("undefined");
    }

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: