Javascript Create Json -
i'm trying create , post json message in following format:
var listobjects = []; $.each(results, function(index, value){ var item = new object(); item.title = value.title; item.code = value.code; listobjects.push(item); }); var jsonresult = json.stringify(listobjects); basically create json this:
[{"title":"product 1","code":123456789012}, {"title":"product 2","code":123456789012}, {"title":"product 3","code":123456789012}, {"title":"product 4","code":123456789012}, {"title":"product 5","code":123456789012}, {"title":"product 11","code":123456789012}, {"title":"product 12","code":123456789012}, {"title":"product 13","code":123456789012}] how can if want add metadata json not repeat each item @ top ... this:
category: x type: y ... items: title: ..... code: ...... so category , type define whole items in json not repeated each item ...
how can if want add metadata json not repeat each item @ top
use object wrapper meta data , items array:
var jsonresult = json.stringify({ category: x, type: y, items: listobjects }); i'm assuming there x , y variables; if they're meant literals, put them in quotes.
side note: in javascript, there's no reason use new object. use {}, same thing. can put property initializers within it, rather assigning properties afterward. here's $.each 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 not least: you're doing $.each $.map for:
var listobjects = $.map(results, function(index, value){ return { title: value.title, code: value.code }; });