AnApprentice AnApprentice - 5 months ago 19
jQuery Question

jQuery how to $.map over a dynamic length of an array

I have the following:

transformResult: function(response) {
if (response && response.buckets && response.buckets[0] && response.buckets[0].documents) {
return {
suggestions: $.map(response.buckets[0].documents, function(dataItem) {
return { value: dataItem._id, data: {
key: response.buckets[0].key,
url: dataItem.url
}
};
})
};

}


I'm using
response.buckets[0]
to ensure at least one bucket exists in the array. There can be 0 or 1+ buckets. The problem is, now the suggestions are just returning for the first bucket w [0] in
response.buckets[0].documents


How can I get the suggestions to return for 0 or more
$.map(response.buckets[0].documents


Thanks

Update

transformResult: function(response) {
var suggestions = {
suggestions: {}
};

if(!response || !response.buckets) {
return suggestions;
}

for(var i=0;i<response.buckets.length;i++) {
var bucket = response.buckets[i];
if(!!bucket.documents) {

suggestions.concat($.map(bucket.documents, function(item) {
return {
value: item._id,
data: {
key: bucket.key,
url: item.url
}
}
}));



};
}

return suggestions;

},


This is now erroring w:
Uncaught TypeError: suggestions.concat is not a function

Answer

I'm not entirely sure wether I got your intention and data-structure right, but I think you're looking for this:

transformResult: function(response) {
    //seems that $.map() doesn't handle null-values :( 
    //so I have to take care of this
    var emptyArray = [];
    return {
        suggestions: $.map(response && response.buckets || emptyArray, function(bucket){
            //jQuerys map-implementation is actually more like a fmap.
            //so this doesn't return an Array of Arrays, but one flat Array instead
            return $.map(bucket.documents || emptyArray, function(document){
                return { 
                    value: document._id, 
                    data: {
                        key: bucket.key,
                        url: document.url
                    }
                }
            });
        })
    }
}