如何从js中的对象数组中切片?

时间:2018-10-31 04:12:29

标签: javascript arrays lodash

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

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

尝试切片前2个,然后切片2个,等等。

如何一次将两本书切成薄片?

8 个答案:

答案 0 :(得分:2)

Array.prototype.slice()

  

slice()方法将数组的一部分的浅表副本返回到从开始到结束(不包括end)选择的新数组对象中。原始数组将不会被修改。

尝试for循环,每次迭代以2为增量。将i的当前值作为 start 位置,将i+2作为 end 位置作为方法参数:

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

答案 1 :(得分:1)

您可以使用切片功能将书籍数量(即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);

请注意,切片不会更新books数组,但会返回一个新数组。

答案 2 :(得分:1)

使用一次滑动的寡妇迭代器,一次迭代两套书籍

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

答案 3 :(得分:1)

由于您使用的是lodash,因此可以使用_.chunklodash#chunk)填充一个数组,该数组包含前2个,然后是2个,依此类推...…… >

_.chunk(books, 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}
  ],
  res = _.chunk(books, 2);
  
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

现在,您有了分块的数组,进行迭代并逐项获取您真正需要的东西!

答案 4 :(得分:1)

您可以尝试使用这种切片方法

return books.slice(0,2).map((book, i) => {
      return;
    });

答案 5 :(得分:0)

您可以一次使用from multiprocessing.pool import ThreadPool as Pool # from multiprocessing import Pool from random import randint import time, os from multiprocessing import Queue def process_line(l): print("{} started".format(l)) time.sleep(randint(0,3)) print("{} done".format(l)) def get_next_line(): with open(sample_csv, 'r') as f: for line in f: yield line # use for testing # def get_next_line(): # for i in range(100): # print('yielding {}'.format(i)) # yield i def worker_main(queue): print("{} working".format(os.getpid())) while True: # get item from queue, block until one is available item = queue.get(True) if item == None: # shutdwon this worker and requeue the item so other workers can shutdown as well queue.put(None) break else: # process item process_line(item) print("{} done working".format(os.getpid())) f = get_next_line() # use a multiprocessing queue with maxsize q = Queue(maxsize=5) # start workers to process queue items t = Pool(processes=8, initializer=worker_main, initargs=(q,)) # enqueue items, this blocks if queue is full for l in f: q.put(l) # enqueue the shutdown message (i.e. None) q.put(None) # need to first close the pool before joining t.close() t.join() 循环,每次执行2个步骤来建立索引,并根据当前索引进行切片。

for

即使书数奇数也可以使用

答案 6 :(得分:0)

您也可以尝试以下代码段-

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)]

答案 7 :(得分:0)

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