0

I am getting a random key value pair,Can i assign it to an array?

Its problematic here when I assign it like arr[50] = 'abc' it automatically creates the keys upto 50 like arr[0],arr[1],arr[2] and so on.

and i wanted an array like this arr[50=>'abc','40'=>'pqr','53'=>'lmn']

I have it here

if(typeof(feedArr.latestRating) == 'object'){ 
                  jQuery.each(feedArr.latestRating,function(key,val){alert('key::'+key);
                    if(key in newRatingArr){ 
                    //delete the key if already exists
                      newRatingArr.splice(key,1);

                    }else{
                      //insert the key,value
                        newRatingArr[key] = val; //here is the problem occurs when key is 50 it automatically creates the indexes in the array upto 50 which i dont want
                       // alert('Key between::'+key);
                       // alert('Value between::'+newRatingArr[key]);
                      //newRatingArr.splice(key,0,val);
                    }
                    //alert(key); 
                  emptyRate = 0;

                  });
                }else{
                  emptyRate = 1;
                }

What can i do here?Please let me know.

1 Answer 1

5

Use an object {} instead of an array [].

Objects can act as unordered key-value containers, which is what you seem to be needing here.

// somewhere...
var newRatingArr = {};

// your code.
var emptyRate = true;
if (typeof (feedArr.latestRating) == 'object') {
    jQuery.each(feedArr.latestRating, function (key, val) {
        newRatingArr[key] = val;
        emptyRate = false;
    });
}
Sign up to request clarification or add additional context in comments.

7 Comments

Will the other functions like SPLICE and all work on an object too? AKX?
my other array functions like concat and shuffle are use less if i use objects here AKX
But if you don't have array-like, contiguous data, then you shouldn't force it into an array...
Well i need to use my data which is most convenient to access in array form.Can I do that in objects?like deleting something from an object at certain index, inserting into it and iterating over it to show a result?
You can delete by a certain key (delete x["foo"]);, modify by keys (x["foo"] = 1; (or x.foo = 1;)) and iterate (in no specified order) (for(var k in x) console.log(k, x[k]);), yes.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.