1

Demo

Why does associative array qaObj return 0 length?

 $(function(){
var data = "Q$:I am in.A$: out Q$:whats this A$:Answer";

alert("in");
var str = $.trim(data).replace(/(\r\n|\n|\r)/gm,"");
    var qaObj = new Array();
    if(str != null && str.indexOf("A$:") != -1 && str.indexOf("Q$:") != -1){
        var qaPairs = str.split("Q$:"); /**Eliminate first header part**/
        qaPairs.shift();
        alert(qaPairs);
        for(var counter = 0; counter < qaPairs.length; counter++){
            var qaSplittedArr = qaPairs[counter].split("A$:");
            qaObj[qaSplittedArr[0]] = qaSplittedArr[1];
        }
    }

   alert(qaObj);
   alert(qaObj["I am in."]);
 });

I am not able to send qaObj to php. It shows empty array. So I am not able to loop through.

Why is it happening?

I am sending through ajax.

Vicky Chijwani
  • 10,191
  • 6
  • 56
  • 79
Gibbs
  • 21,904
  • 13
  • 74
  • 138
  • 1
    @GopsAB I don't know if down-vote is the correct action, but your question was not complete / self-contained (not to mention it contained extraneous details like the regex-matching that get in the way of other people helping you). Please see http://sscce.org/ for how to structure example code. – Vicky Chijwani Oct 04 '15 at 11:51

2 Answers2

2

qaObj needs to be an object ({}) here, not an array (new Array()). JavaScript objects are the equivalents of PHP's associative arrays. Updated fiddle: http://jsfiddle.net/p6p8jezu/4/

$(function(){
    var data = "Q$:I am in.A$: out Q$:whats this A$:Answer";

    var str = $.trim(data).replace(/(\r\n|\n|\r)/gm,"");
        var qaObj = {};
        if(str != null && str.indexOf("A$:") != -1 && str.indexOf("Q$:") != -1){
            var qaPairs = str.split("Q$:"); /**Eliminate first header part**/
            qaPairs.shift();
            alert(qaPairs);
            for(var counter = 0; counter < qaPairs.length; counter++){
                var qaSplittedArr = qaPairs[counter].split("A$:");
                qaObj[qaSplittedArr[0]] = qaSplittedArr[1];
            }
        }

    alert(JSON.stringify(qaObj));
    alert(qaObj["I am in."]);
});
Vicky Chijwani
  • 10,191
  • 6
  • 56
  • 79
1

Try making use of pure Javascript objects instead of arrays.

Change the new Array() to {} in order to make an object.

var qaObj = {};

Now you can do your favorite PHP-like associative array assignment on this object as such and achieve the desired result:

qaObj[qaSplittedArr[0]] = qaSplittedArr[1];

Check your console in this DEMO.

Note that the recommended approach to insert elements to an array is to use .push() method, and not as PHP-like syntax that you've used.

Ahmad Baktash Hayeri
  • 5,802
  • 4
  • 30
  • 43