【问题标题】:Compare a array and an object array and push the contents into the new array according to the value specified比较一个数组和一个对象数组,并根据指定的值将内容压入新数组
【发布时间】:2020-09-02 13:33:40
【问题描述】:

data = [ '1', '2','2] objlist = [ { name : 'dummy' } , {name: 'new' }, { name : 'news'},{name : 'place'}....] - 5 objects

result = [ [{name:'dummy'}], [{name:'new'},{name:'news'}],[{name : 'place'},...]]

所需的结果是所需的结果数组。由于我是新手,因此无法继续进行,并且还怀疑这是否可能,如果是建议或javascript中的工作代码会有所帮助,谢谢

我想要的,例如,如果数组数据的值为 ['1','2','2'],则应将包含所有元素的结果对象数组切片并制作成这个 - [[{obj1}],[{obj2},{obj3}],[{obj4},{obj5}]]

【问题讨论】:

  • 您有预期的输出,但请用文字说明您正在尝试做的事情
  • array的数字是什么意思?你想分割数组吗?
  • 我已经详细更新了这个问题,是的,我希望它被切片@NinaScholz

标签: javascript arrays object


【解决方案1】:

您可以将切片部分推送到结果中。

let array = [1, 2, 2],
    objlist = [{ name: 'dummy' }, { name: 'new' }, { name: 'news' }, { name: 'place' }, { name: 'place' }],
    result = [],
    i = 0,
    j = 0;
    
while (j < array.length) {
    result.push(objlist.slice(i, i += array[j++]));
}

console.log(result);

【讨论】:

    【解决方案2】:

    您可以循环遍历您的数字数组,并为每个数字 n 使用 .splice(0, n) 从您的对象数组中获取一个数组块。这将就地修改数组,允许您的下一个 .splice() 获取下一个连续对象。对于您执行的每个.splice(),您可以将.push() this 放入一个结果数组中。

    请看下面的例子:

    function partition([...arr], chunks) {
      const res = [];
      for(const n of chunks)
        res.push(arr.splice(0, n)); // +n to turn the string number into a number (splice will do this conversion for you but you can take care of it explicitly as well)
      return res;
    }
    
    const chunkArr = ['1', '2', '2'];
    const arr = [{ name : 'dummy' }, {name: 'new' }, { name : 'news'},{name : 'place'}, {name : 'foo'}];
    
    console.log(partition(arr, chunkArr));

    上面我正在使用partition([...arr], chunks),它使用destructuring assignment syntax 来执行输入数组的浅拷贝。这样,当您在函数中使用 .splice() 修改它时,它不会更改传入的数组。

    【讨论】:

      猜你喜欢
      • 2013-05-17
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多