views:

48

answers:

1

There has to be a better way of writing the js in my function....

I need to end up with bare json that looks like this [1095365, 1125504].

Setup of code example;

var article = {"Id":0,"dirtyFlags":null,"textAreas":null,"metaData":null,"relatedCIs":[{"Id":1095365,"Type":4},{"Id":1125504,"Type":4}],"clients":[{"Id":992754}]};
myFunction(article.relatedCIs);

and here's the function i want to optimise;

function myFunction(jRelatedCIs) {
  var idArray = [];
  $.each(jRelatedCIs, function (i, ci) {
    idArray.push(ci.Id);
  });

  var jIdArray = $.toJSON(idArray);

  ....other code
}
+1  A: 

What's suboptimal about what you're doing at the moment? Maybe "optimise" wasn't the right word :)

You could avoid the need for the extra id array by doing it as a one-liner using map, but it's still doing roughly the same thing under the hood:

var jIdArray = $.toJSON($.map(jRelatedCIs, function(ci){return ci.Id;}));
insin
Ah, $.map. It had slipped my mind. Cheers. :)
GordonB