将新属性添加到FOR循环内的现有JSON

时间:2015-11-07 05:13:39

标签: javascript json angularjs

我正在尝试使用来自数据库的更详细的JSON文件填充bootstrap-carousel。我正在添加JSON详细信息以便详细了解。早期的My JSON文件是:

old.json

[
{"screen": [{
    "img" : "../static/images/product/34.jpg",
    "price": "Rs 100",
    "href": "#mobile/1234"
},{

    "img": "../static/images/product/34.jpg",
    "price": "Rs 101",
    "href":"#mobile/1234"
},{

    "img":"../static/images/product/34.jpg",
    "price": "Rs 102",
    "href":"#mobile/1234"
},{

  "img":"../static/images/product/34.jpg",
  "price": "Rs 103",
  "href":"#mobile/1234"
}

]},
 {"screen": [{
    "img" : "../static/images/product/34.jpg",
    "price": "Rs 100",
    "href": "#mobile/1234"
},{

    "img": "../static/images/product/34.jpg",
    "price": "Rs 101",
    "href":"#mobile/1234"
},{

    "img":"../static/images/product/34.jpg",
    "price": "Rs 102",
    "href":"#mobile/1234"
},{

  "img":"../static/images/product/34.jpg",
  "price": "Rs 103",
  "href":"#mobile/1234"
  }
 ]}
]

现在,我正在尝试用更详细的JSON文件填充它。

new.JSON

[
 {
    "sku": "d58a2ece-4387-41d0-bacb-c4b7935f8405",
    "selectedQtyOptions": [],
    "selectedSize": "",
    "description": "obviate buffoonery exterminating knave uncertainly engulf radiantly dogmatist squadron overcame refinance mopes pastier microphone awaiting begin extinguish plenty prod antecedent holdout schoolmarms Rush Kurosawa clinic Broadways Brie sunnier drove ermine husk gendarme vizier Mithridates feast goggled phase purchasing savviest prologs emails resets admire kilotons maladjustment burns viscounts puked receive Tibetans classifications kneed filtration thorns supply bigness astigmatic butterier differential sensational modernistic Djakarta splint earplug boomed horticulture perishables chanticleers syndicated scantiest cantankerousness splashier variate gneiss permutations typeset protozoa wrangled lawbreakers rumbling describe acerbity revenged golfs stalwart stockading caricatures pannier unpleasant sitter rescinds hazing Burgess coastlines thieved encouragingly forefinger Walpole achieving began spec diabetes Lichtenstein hickory squanders borne compute required bringing remunerative Oreo Pekingeses visualized sociopaths radicals flowerier Pakistan terse fillets barking causes Casey manpower ram glamourize deserves Steuben privatized waterproofs ridding poisons discredits overlong coquettes lichees proclivity floating thousandth Linwood promenading mushroomed stain strode obtusest transiency buckets vanguards straying castigate fathom Sappho restricting rehabilitation restiveness pattered bluest box lacquer noticeably Douro overdone biennially diodes baroque hesitant cleaving corroborates reminiscing disks abundant seven used peremptory employment matchbook fraternizing marigold Diaz vaporizers uncork Royal quick absurder misanthropic nabob blindfolds contemplatives Poincaré Galapagos Willamette punctilious Concord Othello carpal leanness Viacom snorkelers arcs piggybacking pulverized",
    "selectedQty": "1",
    "title": "dibble",
    "brand": "Brand7",
    "images": [
        {
            "image0": "/media/products/9f9734f60620cb52246e9e995b75a9bb.jpg"
        }
    ],
    "sizeQtyPrice": [
        {
            "discountAttributes": "upraised saline frowzy rails clampdown Geritol answer devoutest pressure silky",
            "measureUnit": "ltr",
            "discountPercent": 3,
            "mrp": 8472,
            "qty": 6,
            "size": 99
        },
        {
            "discountAttributes": "servers ambitiousness billeted brutalized moonstone clerestory Pole hamlet Shelton testaments",
            "measureUnit": "ltr",
            "discountPercent": 20,
            "mrp": 2477,
            "qty": 4,
            "size": 19
        },
        {
            "discountAttributes": "reeducated schmaltz gnashes marketplaces spill gazetteer bethinks preheats duel parley",
            "measureUnit": "gms",
            "discountPercent": 13,
            "mrp": 6162,
            "qty": 9,
            "size": 86
        }
    ],
    "id": 1
},
{
    "sku": "b8ea355d-7acc-455b-a55c-027b0e5c73cd",
    "selectedQtyOptions": [],
    "selectedSize": "",
    "description": "Krasnodar karats northeasters libertarian aromatherapy badly partings sexpot rectangular Pyrenees yeshivahs gybe hollowness attune reuse Alphard Chilean johns Clydesdale acronym marmots itched proposer lushes hush combinations Latino weeps starches Hinayana firmware gamy society gaggle mast ginseng sordidness spiritualist sacking southern niceties grunting oblation arbor measures hobo measured iPad respites rutting sickened Baylor torturers malingers deferring expurgations tighter tenderfoot upload hosteling Apollonian upscale wraps Suzhou bookworm clarioning Ismail filthiest arborvitae descender accountant rendezvousing Didrikson mesquite sedating warlocks whips filigrees skylarking wallet refill inveighs thatch toffees recognizable Nazca foresails clangor eliminate crapped gourds impinges relinquishing duh drizzliest false uncommitted exhibited inhalation fomented crestfallen Bacall Darwinism Laurel gays peter undiluted showoff groceries sleeting immaturity Barclay whimpered Madeleine typhoons afforesting Theodoric beaching Decker merriness cultures luggage subscriptions Thomas map stun lengths Jackie offshoot Condorcet squirting upholstering amber statures unmanning snuck expatriates Gethsemane mongeese rocket reappearances Mantle marinading grotto twinkled stonewalling intermarried yoga vassal magnums parking convening Senecas sculled crimps undisciplined Montoya matchstick Sarah scissors intellects replay Rover seduce forage land Platonic wafer medicinal wooding Cumberland ravishing plummeting bantam choking rhizome Wei skyrocketed tempting concretely Siberia boxed heliotropes crummy alliteration reappears Budweiser lecher blunts supplications perspiring corrective military scurvy so monitoring tossed thymi saprophyte riverbed",
    "selectedQty": "1",
    "title": "nark",
    "brand": "Brand2",
    "images": [
        {
            "image0": "/media/products/2f08f1c38a7b67956e4f9295b6898f36.jpg"
        }
    ],
    "sizeQtyPrice": [
        {
            "discountAttributes": "towns Emily chafing boozers secrete confidentially primitively hospices disarrange misplaces",
            "measureUnit": "gms",
            "discountPercent": 8,
            "mrp": 9942,
            "qty": 8,
            "size": 67
        },
        {
            "discountAttributes": "amateurish tribune luxuriates staged severity Mia spices Muenster coercion obscure",
            "measureUnit": "ml",
            "discountPercent": 18,
            "mrp": 3104,
            "qty": 8,
            "size": 43
        },
        {
            "discountAttributes": "hanger hassling misanthropists scary dimly economists Moslem castaway Elam initiative",
            "measureUnit": "gms",
            "discountPercent": 17,
            "mrp": 6260,
            "qty": 6,
            "size": 72
        }
    ],
    "id": 2
},
{
    "sku": "7e46f4b1-a083-4eab-8d41-ac594202bd8f",
    "selectedQtyOptions": [],
    "selectedSize": "",
    "description": "avails leg whisking lamaseries rebuilding syllabifying clammiest pretense redcap bellying healthy spaghetti Velveeta shares refunding yellowed danced Peking Darrin pigging illegibly foreign utterly Shakespearean trammelling reports Moran tab okra yipped motorcyclists sweetheart sickbed Serb disgorging Sawyer the incinerator selects each reheats declaimed equestriennes Rolvaag membrane tinselled propagation sighs engraved spookier splurged neuters impersonator Gloucester condemnatory adumbrate citadels Iaccoca mishandled clamming scurries militancy interviewing seized mestizoes lithe Marrakesh isolationism antimatter gossip humanitarians combated tease battering idlers sunset Quaternary striving pattern Brandon heart upended barbiturate overtakes pendant tripe doomsday pejoratives paltriness share tadpoles warming intern fluorides Arawakan honcho sleepiness incorporates typesetters alphabetizes violinists Flanders publicist informer deathbed getaways Iyar Decca schmoozing Tricia ultrasound debugging trepidation suspenseful scrapping rubies exorcized riffling vasectomy tolled bootblack Lott balking PhD hitched utter reprehends snorkel dodges deck dynamical planting conspicuously mottoes totality bedecking bachelor wooed mummification risks Chase weatherproof pear backboard Lieberman fisherman propositional swig ruminants Deena pastiche snob overshadowing spinet apostasy immigrated weighing Christie upraised accruals amphitheatre southwester bulldogs Caracas Trajan primly snowsuit bottomed Woolworth predate biking drill japans potholders uncommon swagging oversteps appositive razing helixes ninetieths prohibitory careered Costello musketeers orator pothooks dumfound express hopelessly franchisers blames semimonthlies transformers histogram radiator canes photoelectric pelves bruised",
    "selectedQty": "1",
    "title": "Harare",
    "brand": "Brand8",
    "images": [
        {
            "image0": "/media/products/2f08f1c38a7b67956e4f9295b6898f36_btZCYFi.jpg"
        }
    ],
    "sizeQtyPrice": [
        {
            "discountAttributes": "deters pyrite excitement Australian wadi protagonists bumpiest Caxton bundling monotony",
            "measureUnit": "ltr",
            "discountPercent": 5,
            "mrp": 9355,
            "qty": 1,
            "size": 80
        },
        {
            "discountAttributes": "puppies smudge moderator constellations invasion Asgard goggle compendiums atrophy tents",
            "measureUnit": "Kg",
            "discountPercent": 7,
            "mrp": 4183,
            "qty": 2,
            "size": 19
        },
        {
            "discountAttributes": "jailer allotting kindness veers Moss invalidation Brahmanism xenophobia warmhearted looping",
            "measureUnit": "ml",
            "discountPercent": 16,
            "mrp": 1956,
            "qty": 1,
            "size": 33
        }
    ],
    "id": 3
},
{
    "sku": "d1cd71a8-9dc5-4724-b269-473ede28a1d7",
    "selectedQtyOptions": [],
    "selectedSize": "",
    "description": "foolish interpolates trumpet monographs ferried inboards Forster tike grammatically sunroof vaporizing Sweden demure retouching completely robbing readies unloose guiltless tatty unobservant cuffs fortieth wither rigorously paradoxically snowmobiling charts clenching planning dealing lesions bicameral pertly chaffinches grumpiness private purled insanely attainment proposal Fatima execrates pshaws chars actuators turboprop soughed kicking majors conquistadores Cynthia septuagenarians kneecaps titans attractions larvas invigorating trunking Shevat recluse Trina slenderness kinking falsified logistically hogged skyrocketing ordinal avoiding trademarked underfoot garter sacrificial pricey nosedive bachelors deiced heave dictatorial muffing prayed rewinding recopied limpidly Crichton conversion chitterlings signets Aiken Froissart turnoff snowshoe forded spiralled underwriters flourishes Sade splicer transfusions cesspools lifelike ruckus showering paean voguish Buck copings Russell watchdog magneto pored height zodiac motherland backings Venus obeys scooters nonintervention dinosaur unashamedly anathema hibernate consumerism portended worked mystically existentialist dissatisfies badgers unanimously triplicated Jenny sagacity Windex snoopier nonplusing shovelling Assam putty darn Sulawesi Italians gunnery codify develops rhinos upwards Louise welled experiences socks pinky mewed Camille claimants swirl squattest ware parenthetic bonitoes hydrangeas decolonizing omit skyjacks Gorky financiers province flywheel southeastward Bayeux updated yowl Tulsidas macintosh sprees pralines systolic uncommoner cilium tromping Asimov heinous cordoned combated camerawomen syndrome identified prizefights heavyweight vertically reflector integrity Hebrides sepulchral loner parrot smooths candidness",
    "selectedQty": "1",
    "title": "viragoes",
    "brand": "Brand0",
    "images": [
        {
            "image0": "/media/products/f791a316ced7b3b774bd61e138197224.jpg"
        }
    ],
    "sizeQtyPrice": [
        {
            "discountAttributes": "chinos theosophy misdemeanor irrigates school Pullman sombrely suspect vortex baddest",
            "measureUnit": "ltr",
            "discountPercent": 4,
            "mrp": 3102,
            "qty": 7,
            "size": 66
        },
        {
            "discountAttributes": "Molotov absurd traces pounces contracts clarions thighbone Hesse parricide constrains",
            "measureUnit": "m",
            "discountPercent": 16,
            "mrp": 2773,
            "qty": 7,
            "size": 18
        },
        {
            "discountAttributes": "detainment gunnysack vied expropriation unobtrusive collectables embracing poster hexing governess",
            "measureUnit": "m",
            "discountPercent": 6,
            "mrp": 9920,
            "qty": 6,
            "size": 69
        }
    ],
    "id": 9
},
{
    "sku": "838660bb-7ab9-4f2a-8be7-9602a5801756",
    "selectedQtyOptions": [],
    "selectedSize": "",
    "description": "agreeing vizier bleariest trig appliquéing copulating commissariats Balzac lunchtimes glittery quacking Leoncavallo heehawing Tampax lizards pegged nanosecond centigrade subplots tumbrils give jawed skits nickel discontinues impinged evangelized Platonist waterlines dams symposiums intercessor cognition heavier softener dromedaries bravos immobilize consciously Clemons patch klutzier Kirkpatrick caddying designs Dulles twelfths undemocratic isolationists infected ma homering soliciting minibus pluralism fraternity catalyzed Scorpio pandemonium waxwing starter infuses rebuttals spirals rerunning interrogatories Manuel whomsoever tenderized conjoint baronesses callower parenthetic plusses extend cockier Fokker dewlap Cowper Swammerdam secs hock relaxations Judas Canadian presidency lo wildness Philippe picture beekeeper lull manuals transnational yaw chloroformed perennials distinctive Nottingham antiquaries underneath parted nervously basemen observatories scrubbed encoder egalitarians winnow caddish Hawaiians brownstones robbing exhaustible antagonist benefactresses Plasticine Peace platypi Guzman stippled shuts peacemakers butterfly Bolton grout McCain Lebanon bounce oleander Balkans endearments snowfall spoonerisms furnaces inequities billowy jutting guffaw beautifully penis newtons snuffboxes j Angelita tinkles literature depicts insouciant scribblers blinker disobediently devotees primordial sixties Kalamazoo shear contest classes cripple edging exactest cheat invocation thrived drunkenness Fuller architectures sprite Lillian constricts tucking chastisements walruses guzzlers rejoinder apprenticeships pillory spendthrift omens spoonful contortions precociously intensely motorway guts cahoot sculptor paralytics reminisce meltdown trusts lady pronghorn scurried Campbell micron flawing foals nigher",
    "selectedQty": "1",
    "title": "smokier",
    "brand": "Brand2",
    "images": [
        {
            "image0": "/media/products/f51a649e72694d23962ee77a97872f0e.jpg"
        }
    ],
    "sizeQtyPrice": [
        {
            "discountAttributes": "Beerbohm earldom Stanley seconding hypertension Sayers miserly epitome retires ditching",
            "measureUnit": "m",
            "discountPercent": 15,
            "mrp": 5065,
            "qty": 6,
            "size": 83
        },
        {
            "discountAttributes": "confine Newman bagel cornflower rears generator goaded midweeks drain cigarillo",
            "measureUnit": "Kg",
            "discountPercent": 12,
            "mrp": 2284,
            "qty": 9,
            "size": 13
        },
        {
            "discountAttributes": "eerier fizzes lessened rotisserie developer Gray industrial callused convergences ampoule",
            "measureUnit": "gms",
            "discountPercent": 4,
            "mrp": 6816,
            "qty": 8,
            "size": 18
        }
    ],
    "id": 14
}
]

正如您所看到的,我需要将我的new.JSON分组为屏幕属性下的一组4。为此我写了一个for循环:

mainApp.controller('MultiCarouselController', function($scope, $http) {

$scope.products = [];
$scope.Math = Math;
$http.get("/get_broad_category_products/?BroadCategory=BroadCategory3")
        .success(function (response) {
            $scope.products = response;
            var iteratation = Math.ceil($scope.products.length/4);
            var carouselJson = [];
            for(var index = 0; index < iteratation; index++){ // kinda 2D matrix as [0,1],[0,2],[1,1],[1,2]
               var temp = [];
               for (var i = (index*4) ; i < (4*(index+1)) ; i++){
                    temp = temp.concat($scope.products[i])  // concatenating 4 JSON as a group
                }
                carouselJson.push(temp);  // pushing group to new JSON
            }
            console.log(carouselJson);
     }).error(function(){
            console.log('Error happened ... ');
     });

 });

angularJS controller工作正常,如何添加&#34; screen&#34; 属性,然后向其添加4个JSON组

我虽然做了类似的事情:

 for(var index = 0; index < iteratation; index++){ // kinda 2D matrix as [0,1],[0,2],[1,1],[1,2]
   var temp = [];
   for (var i = (index*4) ; i < (4*(index+1)) ; i++){
      temp = temp.concat($scope.products[i])  // concatenating 4 JSON as a group
   }
var jsTemp = [] ;                
carouselJson.push(jsTemp.screen.push(temp));  // Errrrr.... screen property is not there in jsTemp. Now ????
 }

小帮助可能会起到作用!!!

3 个答案:

答案 0 :(得分:1)

我根本不是角色的粉丝所以不知道它如何处理JSON。

然而,JSON只是一个序列化的对象,因此只要您采取一些预防措施,它就很容易混合和匹配。

考虑以下两个json文件。 JSON1是产品列表,每个产品都有一个该产品唯一的ID。第二个JSON JSON2修改了第一个JSON,它具有特定名称“extraImages”,“newItems”,“updates”,“newData”,我们必须添加到第一个。 连接它们不会,因为它们不是数组。你也不能只是连接JSON字符串,它不起作用。 您可以编写一个通用的对象连接函数,但这将加入两个没有任何上下文知识。它如何知道放置额外图像的位置?如何知道每个产品都可以通过ID识别?

要加入这两个对象,我们需要了解两个文件中每个项目的数据结构和语义含义。

无论如何将两个JSON文件作为字符串。

var JSON1 = `{
    "item1":{
      "id":100,
      "desc":"a product",
      "images":[
          "img1.jpg",
          "img2.jpg",
      ]
     },
    "item2":{
      "id":101,
      "desc":"another product",
      "images":"img11.jpg",  // this item has only one image so it just has a string
     },
    "item5":{
      "id":105,
      "desc":"a product without images",
     },
  }`;
var JSON2 = `{
   "extraImages":[{
        "id":101,
        "images":[
            "imageA.png",
            "imageC.png"
        ]
    }],
   "newData":[{
        "id":100,
        "price":100,
        }
    ],
   "update":[{
       "id":100,
       "desc":"Best buy product",
       }
    ],
    "newItems":[{
      "item3":{
        "id":102,
        "desc":"Just on the docks",
        "images":[
            "Blury11.jpg",
        ]
      },
     }
}`

因为字符串JSON是没用的。难以搜索和查找数据。所以JavaScript有一个内置对象来处理JSON,称为有趣JSON

JSON对象有两种方法JSON.stringify(Obj)JSON.parse(String)

  1. JSON.stringify采用基本的JS数据类型并将其转换为 JSON字符串。
  2. JSON.parse从任何来源获取json字符串并进行转换 它回到JS Object,Array ......
  3. 首先,将JSON字符串转换为对象。

    var items = JSON.parse(JSON1);
    var extras = JSON.parse(JSON2); 
    

    现在我们有两个可以操作和加入的普通JS对象。

    让我们做图像。额外的图像是一个数组,每个项目都有一个ID和一组图像名称。

    // we know the name of the object that has extra images so check if its there 
    // and then itterate all the items in the array 
    if(extras.extraImages !== undefined){ // Does this property exist
         extras.extraImages.forEach(function(item){  // itterat over each item
             var arrayOfImages;
             // do the images exist and if so are they as an array
             if(item.images !== undefined && typeof item.images === "array"){
                   arrayOfImages = item.images;
             }
             // the data structure may vary depending on what is serving the JSON
             // data so you can add code to take differing types 
             // Now to find the matching item in the items object
             // check that there is an array of images to add and tha
             // the item we have has an item id we can use to find the existing item
             if(arrayOfImages !== undefined && item.id !== undefined){ 
                 // continue on further down
    

    因此我们找到了一个额外的图像项目,其中包含ID和图像名称数组。我们需要找到具有该ID的产品。正如我们将要做的那样,我们可以多次写一个函数来做到这一点。

     // pass the items object that may contain the item with the ID we are looking for
    function getItemById(items,id){ 
         for(var itemName in items){  // iterate each named item. itemName is 
                                      // just a variable it could be any var name.
                                      // It contains a string holding each enumerable 
                                      // properties name in turn
    

    现在检查指定的属性是否有id,你可能想要检查id是否具有我们正在寻找的id。

    if(item[itemName].id === id){

    如果项目没有id,则会抛出错误,并且有许多原因可能会出现无法正确构造的可枚举属性。因此检查id是否存在然后检查其值。与C / C ++ / C#不同,比较的顺序始终是从左到右。在第一个错误时,if(将退出()而不进行任何进一步的比较。 因此,只要您首先测试它不会抛出ReferenceError: id is not defined

    ,就可以安全地在javascript中测试第二个条件

    if(items[itemName].id !== undefined && items[itemName].id == id){

    永远不会抛出错误

    if(items[itemName].id == id && items[itemName].id !== undefined ){

    如果id不存在,则可以。

    无论如何我分歧。

               if(items[itemName].id == id && items[itemName].id !== undefined ){
                     // found the item with matching id
                     return items[itemName]; // so return it
               }
          }
          return undefined; // nothing found that matches so return undefined
       } //end of function
    

    回到添加额外的图像。我们刚刚测试过,发现了一个带有id和一些额外图像名称的extraimage项目。

                 // use the function to get the item
                 var existingItem = getItemById(items,item.id);
                 // check that we found one
                 if(existingItem !== undefined){
                     // check to see if it has a images
                     if(existingItem.images === undefined){
                          // no image so creat images and add an empty array
                          existingItem.images = []
                     }else  // if it does is it an array
                     if(typeof existingItem.images !== "array"){ 
                         // not an array we will assume what is there
                         // is an image description of some type
                         // so convert the existing images object into
                         // an array and add the existing item into it
                         existingItem.images = [existingItem.images];
                     }
                     // now we are sure the images array is correct so lets
                     // add the new images to i
                     existingItem.images existingItem.images.concat( arrayOfImages);
                  }
              }
         }); // end of forEach lop
      } // endo of adding new images
    

    所以把它包起来

    // code to join extraImages to items
    if(extras.extraImages !== undefined){ 
         extras.extraImages.forEach(function(item){ 
             var arrayOfImages;
             if(item.images !== undefined && typeof item.images === "array"){
                   arrayOfImages = item.images;
             }
             if(arrayOfImages !== undefined && item.id !== undefined){ 
                 var existingItem = getItemById(items,item.id);
                 if(existingItem !== undefined){
                     if(existingItem.images === undefined){
                          existingItem.images = []
                     }else 
                     if(typeof existingItem.images !== "array"){ 
                         existingItem.images = [existingItem.images];
                     }
                     existingItem.images existingItem.images.concat( arrayOfImages);
                  }
              }
         });
      } 
      // was going to show all the other joins for extras.update, newItems, and newData 
      // too much for one answer.
    

    我认为这是一个很长的答案。我假设你看到正在做什么以及如何使用它来将两个对象连接在一起,同时符合它的语义。您应该能够编写一个函数来为您的数据执行相同的操作。通过JSON.parse将两个JSON字符串转换为对象,迭代对象结构,遵循数据的语义,根据需要创建或附加数据。

    最后,我假设您需要将连接数据作为JSON字符串,将更新后的对象转换回json字符串。

    JSON1 = JSON.stringify(items); // convert the updated items object to a JSON string
    

    现在你可以将它传回Angular的JSON抽象层来完成你需要的工作。

    希望这会有所帮助。也许在Angular中有一种方法,但由于没有人回答所需的东西,我不想玷污我的纯粹方式(令人讨厌的Angular),这将给你一些额外的JS基础并允许你解决你的问题。

答案 1 :(得分:0)

如果我正确读取此内容,您需要将新属性添加到temp数组中的每个元素。为此,您可以尝试从$scope.products[i]创建新对象。

for(var index = 0; index < iteratation; index++){ // kinda 2D matrix as [0,1],[0,2],[1,1],[1,2]
   var temp = [];
   for (var i = (index*4) ; i < (4*(index+1)) ; i++){
      var destObj = $scope.products[i];
      destObj.screen = 'xx' // Assign your value here.
      temp = temp.concat(destObj)  // concatenating 4 JSON as a group
   }
carouselJson.push(temp);
 }

希望这会有所帮助......

答案 2 :(得分:0)

这个链接帮助了我

JavaScript Array Push key value

改变了我的循环:

var carouselJson = [];
for(var index = 0; index < iteratation; index++){ // kinda 2D matrix as [0,1],[0,2],[1,1],[1,2]
      var temp = [];
      var screen = ['screen'];
      var obj = {};
      for (var i = (index*4) ; i < (4*(index+1)) ; i++){
          temp = temp.concat($scope.products[i]);  // concatenating 4 JSON as a group
         }
      obj[screen]=temp;
      carouselJson.push(obj);  // pushing group to new JSON
     }
   $scope.mCarousels = carouselJson;