Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 向FOR循环内部的现有JSON添加新属性_Javascript_Json_Angularjs - Fatal编程技术网

Javascript 向FOR循环内部的现有JSON添加新属性

Javascript 向FOR循环内部的现有JSON添加新属性,javascript,json,angularjs,Javascript,Json,Angularjs,我试图用数据库中一些更详细的JSON文件填充引导转盘。我添加JSON细节是为了详细理解。之前我的JSON文件是: // code to join extraImages to items if(extras.extraImages !== undefined){ extras.extraImages.forEach(function(item){ var arrayOfImages; if(item.images !== undefined &a

我试图用数据库中一些更详细的JSON文件填充引导转盘。我添加JSON细节是为了详细理解。之前我的JSON文件是:

// 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.
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"
  }
 ]}
]
// 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文件填充它

// 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.
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
}
]
// 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.
如您所见,我需要将我的
new.JSON
分组为screen属性下的一组4。为此,我为循环编写了一个:

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 ... ');
     });

 });
// 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.

小小的帮助可能会奏效

如果我读得正确,您希望在
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);
 }
// 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.
for(var-index=0;index

希望这能有所帮助……

我一点也不喜欢angular,所以不太了解它如何处理JSON

// 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只是一个序列化对象,因此只要采取一些预防措施,就很容易混合和匹配

// 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文件。JSON1是一个产品列表,每个产品都有一个唯一的id。第二个JSON
JSON2
对第一个JSON进行了修改,修改后的JSON具有我们必须添加到第一个JSON的特定名称“extraImages”、“newItems”、“Update”、“newData”。 连接它们不会起作用,因为它们不是数组。您也不能只解析JSON字符串,它不起作用。 您可以编写一个通用的对象连接函数,但它将在没有任何上下文知识的情况下连接这两个函数。它如何知道在哪里放置额外的图像?它如何知道每个产品都可以通过ID识别

// 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.
为了连接这两个对象,我们需要对两个文件中的数据结构和每个项目的语义有一定的了解

// 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文件都是字符串

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",
        ]
      },
     }
}`
// 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有点无用。难以搜索和查找数据。因此JavaScript有一个内置的对象来处理JSON,这个对象被称为非常有趣的
JSON

// 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
对象有两个方法
JSON.stringify(Obj)
JSON.parse(String)

// 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.stringify
    采用基本JS数据类型并将其转换为 JSON字符串
  • JSON.parse
    从任何源获取JSON字符串并进行转换 它返回到一个JS对象、数组中
  • 所以,第一步是将两个JSON字符串转换为对象

    var items = JSON.parse(JSON1);
    var extras = JSON.parse(JSON2); 
    
    // 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.
    
    现在我们有了两个普通的JS对象,可以对它们进行操作和连接

    // 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.
    
    让我们来做图片。额外的图像是一个数组,每个项目都有一个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
    
                 // 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.
    
    因此,我们找到了一个额外的images项,它有一个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
    
    // 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.
    
    现在检查命名属性是否有一个id,您可能会尝试检查该id是否有我们正在寻找的id

    // 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.
    
    if(item[itemName].id==id){

    // 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.
    
    如果项没有id,并且由于多种原因可能出现结构不正确的可枚举属性,则会引发错误。因此,请检查id是否存在,然后检查其值。与C/C++/C不同,比较顺序始终是从左到右。如果第一个false,则
    if(
    将从()不做进一步的比较。 因此,在javascript中测试第二个条件是安全的,只要您先测试它不会抛出
    ReferenceError:id未定义

    // 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.
    
    if(items[itemName].id!==undefined&&items[itemName].id==id){

    // 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.
    
    在任何时候都不会抛出错误

    // 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.
    
    if(items[itemName].id==id&&items[itemName].id!==undefined){

    // 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.
    
    如果id不存在,则可以

    // 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.
    
    无论如何,我有分歧

               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
    
    // 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.
    
    现在回到添加额外图像的话题。我们刚刚测试并发现了一个带有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
    
                 // 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.
    
    所以把一切都结束吧

    // 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将两个JSON字符串转换为对象。解析
    按照e数据的语义,根据需要创建或附加数据

    // 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字符串,就是将更新的对象转换回JSON字符串

    // 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.
    
    JSON1 = JSON.stringify(items); // convert the updated items object to a JSON string
    
    现在,您可以将其传递回Angular的JSON抽象层,以执行您需要的操作

    // 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.
    
    希望这能有所帮助。也许在Angular中有一种方法,但由于没有人回答需要什么,我不想玷污我的纯粹主义方式(令人讨厌的Angular),这将给你一些额外的JS基础,让你解决你的问题。

    这个链接帮助了我

    // 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.
    

    // 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.
    
    将我的循环更改为:

    // 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.
    
    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;
    
    var carouselJson=[];
    对于(var-index=0;index
    您刚刚将
    jsTemp
    实例化为一个新数组……为什么您希望它具有
    屏幕
    属性?@sirrocco:是的,我知道我在问如何实现这一点。我在那次会议上的评论中也提到了同样的问题