具有子数组创建的对象的Javascript数组

时间:2019-01-06 16:24:47

标签: javascript arrays object

我正在开发一个javascript程序,我需要一个对象才能返回到前端。

我写了一些返回的查询:

  • 照片:{id,所有者,链接,描述,名称}的数组
  • 评论:{id,text,photoTarget,userOrigin,name}的// // photoTraget是照片ID

我想创建一个名为photoArray的新数组,该数组将每张照片的注释存储为子数组。

这是结构:

$(document).on('click','#addcommentbtn',function(){
addcomment();
});    

方法:

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

5 个答案:

答案 0 :(得分:0)

您可以通过减少photos数组来使用Map,其中分配了新属性comments,这是地图的值。

然后迭代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));

答案 1 :(得分:0)

首先,您需要将注释数组作为属性添加到图像对象

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

答案 2 :(得分:0)

遍历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));

答案 3 :(得分:0)

一种方法是在构建最终数组时,基于filter为每张照片photoTarget添加注释:

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之类的方法慢,因为它会遍历每张照片的所有评论。

答案 4 :(得分:0)

我已将注释数组简化为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));