[英]How to slice from an array of objects in js?
I have an array of objects like this:我有一个像这样的对象数组:
const books =[
{id: "1", name: "twilight", category: "Movies", price: 10},
{id: "2", name: "jaws", category: "Movies", price: 22},
{id: "3", name: "the shining", category: "Movies", price: 1},
{id: "4", name: "beers", category: "Movies", price: 10},
{id: "5", name: "apples", category: "Movies", price: 22},
{id: "6", name: "mono", category: "Movies", price: 1}
]
Trying to slice the first 2, then second 2 etc.试图切片第一个 2,然后是第二个 2 等。
How can I slice by 2 books at the time?我怎样才能一次切两本书?
Array.prototype.slice() Array.prototype.slice()
The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included).
slice() 方法将数组的一部分的浅拷贝返回到从开始到结束(不包括结束)选择的新数组对象中。 The original array will not be modified.
不会修改原始数组。
Try with for
loop with a increment of 2 in each iteration.尝试在每次迭代中以 2 为增量使用
for
循环。 Pass the current value of i
as the start position and i+2
as the end position as the method parameter:将
i
的当前值作为开始位置,将i+2
作为结束位置作为方法参数传递:
const books =[ {id: "1", name: "twilight", category: "Movies", price: 10}, {id: "2", name: "jaws", category: "Movies", price: 22}, {id: "3", name: "the shining", category: "Movies", price: 1}, {id: "4", name: "beers", category: "Movies", price: 10}, {id: "5", name: "apples", category: "Movies", price: 22}, {id: "6", name: "mono", category: "Movies", price: 1} ] for(var i=0; i<books.length; i+=2){ var sliced = books.slice(i, i+2); console.log(sliced); }
You can use try this slice method你可以使用试试这个切片方法
return books.slice(0,2).map((book, i) => {
return;
});
You can use the slice function passing the number of books to slice (ie 2):您可以使用 slice 函数传递要切片的书数(即 2):
let slicedBooks = []
for(var i = 0;i < books.length;i+= 2){
let part_slice = books.slice(i, 2 + i);
slicedBooks.push(part_slice);
console.log(part_slice);
}
console.log(slicedBooks);
Be careful slice does not update books array, but returns a new array.注意 slice 不会更新 books 数组,而是返回一个新数组。
Use a sliding widow iterator which sides over a set of 2 books at a time使用滑动寡妇迭代器,一次侧翻一组 2 本书
function two_at_a_time(arr, func){
for(var i=0; i < arr.length - 1; i++){
func(arr[i], arr[i + 1]);
}
}
two_at_a_time(books, function(current, next){
console.log(current, next);
});
Since you are using lodash , you can use _.chunk
( lodash#chunk ) to populate a array of array containing first 2, then second 2, and so on...由于您使用的是lodash ,您可以使用
_.chunk
( lodash#chunk ) 来填充包含第一个 2 的数组,然后是第二个 2,依此类推...
_.chunk(books, 2)
Here is an working example:这是一个工作示例:
const books = [ {id: "1", name: "twilight", category: "Movies", price: 10}, {id: "2", name: "jaws", category: "Movies", price: 22}, {id: "3", name: "the shining", category: "Movies", price: 1}, {id: "4", name: "beers", category: "Movies", price: 10}, {id: "5", name: "apples", category: "Movies", price: 22}, {id: "6", name: "mono", category: "Movies", price: 1} ], res = _.chunk(books, 2); console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Now, you have the chunked array, iterate and take one by one item to get what exactly you need!现在,您拥有分块数组,迭代并一项一项地获取您需要的内容!
You can use a for
loop with 2 steps at a time for the index, and slice based on the current index.您可以对索引使用一次 2 步的
for
循环,并根据当前索引进行切片。
for (var i=0; i<books.length; i+=2) {
console.log(books.slice(i, i+2));
}
This also works even if there are odd number of books即使有奇数本书,这也有效
You can also try this code snippet -你也可以试试这个代码片段 -
var chunckedArray = function(books, chunkCount){
var chunks = [];
while(books.length){
chunks.push(books.splice(0, chunkCount));
}
return chunks;
};
chunckedArray(books, 2); // [Array(2), Array(2), Array(2)]
100% equal to php 100% 等于 php
function array_slice (arr, offst, lgth, preserveKeys) { // eslint-disable-line camelcase
// discuss at: https://locutus.io/php/array_slice/
// original by: Brett Zamir (https://brett-zamir.me)
// input by: Brett Zamir (https://brett-zamir.me)
// bugfixed by: Kevin van Zonneveld (https://kvz.io)
// note 1: Relies on is_int because !isNaN accepts floats
// example 1: array_slice(["a", "b", "c", "d", "e"], 2, -1)
// returns 1: [ 'c', 'd' ]
// example 2: array_slice(["a", "b", "c", "d", "e"], 2, -1, true)
// returns 2: {2: 'c', 3: 'd'}
var key = ''
if (Object.prototype.toString.call(arr) !== '[object Array]' || (preserveKeys && offst !== 0)) {
// Assoc. array as input or if required as output
var lgt = 0
var newAssoc = {}
for (key in arr) {
lgt += 1
newAssoc[key] = arr[key]
}
arr = newAssoc
offst = (offst < 0) ? lgt + offst : offst
lgth = lgth === undefined ? lgt : (lgth < 0) ? lgt + lgth - offst : lgth
var assoc = {}
var start = false
var it = -1
var arrlgth = 0
var noPkIdx = 0
for (key in arr) {
++it
if (arrlgth >= lgth) {
break
}
if (it === offst) {
start = true
}
if (!start) {
continue
}++arrlgth
if (isInt(key) && !preserveKeys) {
assoc[noPkIdx++] = arr[key]
} else {
assoc[key] = arr[key]
}
}
// Make as array-like object (though length will not be dynamic)
// assoc.length = arrlgth;
return assoc
}
if (lgth === undefined) {
return arr.slice(offst)
} else if (lgth >= 0) {
return arr.slice(offst, offst + lgth)
} else {
return arr.slice(offst, lgth)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.