how can I do it so that if I want to add some metadata to my json that will not repeat for each item but just at the top
Use an object as a wrapper with the meta data and the items
array:
var jsonResult = JSON.stringify({
category: x,
type: y,
items: listObjects
});
I'm assuming there that x
and y
are variables; if they're meant to be literals, put them in quotes.
Side note: In JavaScript, there's no reason to use new Object
. Just use {}
, which does the same thing. You can also put property initializers within it, rather than assigning to properties afterward. Here's your $.each
with those changes (and indentation):
$.each(results, function(index, value){
var item = {
title: value.Title,
code: value.Code
};
listObjects.push(item);
});
You can, of course, combine those:
$.each(results, function(index, value){
listObjects.push({
title: value.Title,
code: value.Code
});
});
Last but not least: What you're doing with $.each
is exactly what $.map
is for:
var listObjects = $.map(results, function(index, value){
return {
title: value.Title,
code: value.Code
};
});