在每个X对象的对象数组中添加一个对象

时间:2017-09-11 09:26:22

标签: javascript arrays

我有一个像这样的对象数组:

[

 {_id: "59b6433532b60cfc0a253cec", description: "", imagepath: 
 "https://xxx.1", likes: 0, downvotes: 0}

 {_id: "59b6433532b60cfc0a253ceb", description: "", imagepath: 
 "https://xxx.2", likes: 0, downvotes: 0}

 {_id: "59b6433532b60cfc0a253cea", description: "", imagepath: 
 "https://xxx.3", likes: 0, downvotes: 0}

]

使用分页时,此数组变得越来越大(每个10个对象将另一个10添加到数组中,依此类推)。

当数组长度为20,40,60等时,如何在数组中注入新对象?

预期产出:

[

 {_id: "59b6433532b60cfc0a253cec", description: "", imagepath: 
 "https://xxx.1", likes: 0, downvotes: 0}

 {_id: "59b6433532b60cfc0a253ceb", description: "", imagepath: 
 "https://xxx.2", likes: 0, downvotes: 0}

 {_id: "59b6433532b60cfc0a253cea", description: "", imagepath: 
 "https://xxx.3", likes: 0, downvotes: 0}

 ... <--- objects are now 20 
 {new object 1}
 ... <--- objects are now 40
 {new object 1} <--- same object as above
]

2 个答案:

答案 0 :(得分:1)

根据您希望插入新对象的方式,您可以在每次数据检索或循环中使用data.length % 20 === 0。将modulus用于20并与0进行比较,将在长度为20, 40, 60, ...时添加新对象。

var data = [

 {_id: "59b6433532b60cfc0a253cec", description: "", imagepath: 
 "https://xxx.1", likes: 0, downvotes: 0},

 {_id: "59b6433532b60cfc0a253ceb", description: "", imagepath: 
 "https://xxx.2", likes: 0, downvotes: 0},

 {_id: "59b6433532b60cfc0a253cea", description: "", imagepath: 
 "https://xxx.3", likes: 0, downvotes: 0}
];

var modCount = 0;
var objToInject= {type: 'blog_post'};

//after each retrieval of the JSON array as in data, check if length is 20,40,60,... and so on
if((data.length - modCount) % 20 === 0){
  data.push(objToInject);
  modCount++;
}

console.log(data);

答案 1 :(得分:1)

解决方案

处理此问题的最佳方法是使用array reduce

Read more about array reduce here

示例

在以下示例中,我将在每个第4个索引之后添加文本“test”

var mainArray = [1,2,3,4,5,6,7,8,9];
var newArray = mainArray.reduce(function(carry, value) {
     if(carry.length % 4 === 0) {
        carray.puh('test');
     }
     carry.push(value);
     return carry;
}, []);

通过在字符串测试的情况下添加对象,您可以使用相同的方法来获得所需的结果。