簡體   English   中英

具有子數組創建的對象的Javascript數組

[英]Javascript array of objects with subarray creation

我正在使用JavaScript程序,因此需要一個對象才能返回到前端。

我寫了一些返回的查詢:

  • 照片:{id,所有者,鏈接,描述,名稱}的數組
  • 評論:{id,text,photoTarget,userOrigin,name}的數組// photoTraget是照片ID

我想創建一個名為photoArray的新數組,該數組將每張照片的注釋存儲為子數組。

這是結構:

photoArray[0] ={
        id, 
        owner, 
        link, 
        description, 
        name, 
        comment: [id, text, photoTarget, userOrigin, name]
      }

做法:

for(var i=0; i< photos.length; i++){
   for(var j=0; j< comments.length; j++){
      if(photos[i].id == comments[j].photoTarget){

              //I can't get this part to work

       }
   }
}

您可以通過減少photos數組來使用Map ,在photos數組中分配了新的屬性comments ,這是map的值。

然后迭代comments並將數據推送到分配的地圖。

此方法僅使用兩個循環,大O:O(n + m)

var photos = [{...}, {...}, ...],
    comments = [{...}, {...}, ...],
    photoMap = photos.reduce((m, p) => m.set(p.id, p.comments = []), new Map);


comments.forEach(c => photoMap.get(c.photoTarget).push(p));

首先,您需要將注釋數組作為屬性添加到圖像對象

for (var i = 0; i < photos.length; i++) {
   photos[i].comments = [];
}

然后

for(var i=0; i< photos.length; i++){
  for(var j=0; j< comments.length; j++){
     if(photos[i].id == comments[j].photoTarget){
       photos[i].comments.push({comments[j].id, comments[j].text, 
       comments[j].photoTarget, comments[j].userOrigin, comments[j].name});
    }
  }
}

遍歷photos數組並找到匹配的注釋,並將其添加到photo對象的comment數組中。

 var photos = [{id :1, owner:'test'}] var comments = [{id:1, text:'test', photoTarget:1}, {id:2, text:'test1', photoTarget:1}] var photoArray = [] for(var i=0; i< photos.length; i++){ var photo = photos[i]; for(var j=0; j< comments.length; j++){ if(photos[i].id == comments[j].photoTarget){ photo.comment = photo.comment ? photo.comment.concat(comments[j]) : [].concat(comments[j]); //Add a comment property and assign the matching comment object } } photoArray.push(photo); } console.log(JSON.stringify(photoArray)); 

一種方法是在構建最終數組時,基於photoTarget filter每張照片的注釋對象:

const result = photos.map(p =>
  Object.assign({}, p, { comments: comments.filter(c => c.photoTarget === p.id) }));

帶有簡化對象的演示如下:

 const photos = [{"id":1,"owner":"Spence","name":"eiusmod ex"},{"id":2,"owner":"Billie","name":"ullamco officia"},{"id":3,"owner":"Shannon","name":"duis ipsum"},{"id":4,"owner":"Marian","name":"excepteur ipsum"}];; const comments = [{"id":0,"name":"Kendra","text":"reprehenderit sit sunt Lorem","photoTarget":3},{"id":1,"name":"Arline","text":"nisi aliqua in magna","photoTarget":4},{"id":2,"name":"Earlene","text":"proident ex cupidatat eu","photoTarget":3},{"id":3,"name":"Downs","text":"ullamco est veniam enim","photoTarget":1},{"id":4,"name":"Claire","text":"voluptate tempor velit laborum","photoTarget":4},{"id":5,"name":"Louise","text":"amet ea quis ipsum","photoTarget":2},{"id":6,"name":"Simpson","text":"qui velit in enim","photoTarget":1},{"id":7,"name":"Lavonne","text":"ea qui mollit adipisicing","photoTarget":4},{"id":8,"name":"Morris","text":"veniam aliquip esse nisi","photoTarget":1},{"id":9,"name":"Rosalinda","text":"consequat non culpa qui","photoTarget":2}]; const result = photos.map(p => Object.assign({}, p, { comments: comments.filter(c => c.photoTarget === p.id) })); console.log(result); 

這種方法比使用諸如Map類的方法慢,因為它會遍歷每張照片的所有注釋。

我已經將注釋數組簡化為commentsGroupedByPhoto(一個對象,其中photoTarget將是鍵,並且注釋數組具有相同的photoTarget),然后在照片上使用地圖函數生成photoArray,而未修改照片數組

 var photos = [{id :1, owner:'owner1'},{id :2, owner:'owner2'},{id:3,owner:'owner3'}] var comments = [{id:1, text:'comment1 for 1', photoTarget:1, userOrigin: 'Asia'}, {id:2, text:'comment2 for 1', photoTarget:1, userOrigin: 'America'}, {id:3, text:'only comment for 2', photoTarget:2, userOrigin: 'Europe'}] var commentsGroupedByPhoto = comments.reduce(function(commentsObj, comment) { var photoId = comment.photoTarget, commentByPhotoTarget = commentsObj[photoId]; commentByPhotoTarget ? commentByPhotoTarget.push(comment) : commentsObj[photoId] = [comment]; return commentsObj; }, {}); console.log('comments grouped by id --- ' + JSON.stringify(commentsGroupedByPhoto)); var photoArray = photos.map(function(photo){ var photoCopy = {photo}; //ES6 cloning //if your codebase does not support ES6 then use //var photoCopy = Object.assign({}, photo); photoCopy.comments = commentsGroupedByPhoto[photo.id]; return photoCopy; }); console.log('photoArray --- ' + JSON.stringify(photoArray)); console.log('photos --- ' + JSON.stringify(photos)); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM