2015-11-07 122 views
0

我想从数据库中填充一些更详细的JSON文件的引导程序传送带。为了详细理解,我添加了JSON详细信息。此前我的JSON文件是:将新属性添加到FOR循环中现有的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工作完全没问题,我怎么可以添加“屏幕”属性,然后添加4个JSONs组给它

不过,我觉得这样做的东西像:

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 ???? 
} 

小的帮助可能做的伎俩!

+0

你刚才实例'jsTemp'到新阵列...为什么你会希望它有'屏幕属性? – sirrocco

+0

@sirrocco:是的,我知道你在问怎么做。我在该评论中提到了同样的内容。 –

回答

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

希望这有助于...

1

我不是在所有角度的风扇所以不很了解如何处理的JSON。

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

请考虑以下两个json文件。 JSON1是一个产品列表,每个产品都有一个该产品特有的ID。第二个JSON JSON2对第一个具有特定名称“extraImages”,“newItems”,“updates”,“newData”的第一个JSON进行了修改,我们必须将其添加到第一个JSON中。 连接它们不会做,因为它们不是数组。你也不能简单地连接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对象,数组...

所以第一步都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(将退出()并且不做任何进一步的比较。 因此在JavaScript安全的,只要你考第一,它不会抛出来测试第二个条件ReferenceError: id is not defined

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和一些额外图像名称的外部图像项目。

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

现在你可以回传给它角的JSON抽象层,你所需要的。

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

+0

谢谢你这么详细的回答。给我很多帮助。 –

+0

谢谢,我很高兴它帮助。 :) – Blindman67