将对象拆分为特定的ID字符串

时间:2019-04-11 14:03:21

标签: javascript arrays

我有类似这样的数据

const data = [
  {
    name: 'name1',
    id: 'id1'
  },
  {
    name: 'name2',
    id: 'id2'
  },
  {
    name: 'name3',
    id: 'id3'
  },
  {
    name: 'name4',
    id: 'id4'
  },
  {
    name: 'name5',
    id: 'id5'
  },
  {
    name: 'name6',
    id: 'id6'
  },
  {
    name: 'name7',
    id: 'id7'
  },
  {
    name: 'name8',
    id: 'id8'
  },

]

我需要将所有id3(不包括id3)的对象推入一个数组,并从id3推到id6(不包括id6)放在一个数组中,其余的东西放在另一个数组中。

id1id3之间将添加任意数量的对象,但是我们需要将其推到id3,方法与我们将id3中的对象数量添加到{{ 1}}。

最后,我尝试达到这样的目的

id6

此处firstArr = [ { name: 'name1', id: 'id1' }, { name: 'name2', id: 'id2' } ] secondArr = [ { name: 'name3', id: 'id3' }, { name: 'name4', id: 'id4' }, { name: 'name5', id: 'id5' } ] thirdArr = [ { name: 'name6', id: 'id6' }, { name: 'name7', id: 'id7' }, { name: 'name8', id: 'id8' } ] id3之类的顺序不会改变,因此我们可以以此为参考。

7 个答案:

答案 0 :(得分:2)

您可以先使用findIndex(),然后再使用slice()

我认为创建firstArr,...之类的变量不是一个好主意,而是可以创建数组数组

const data = [ { name: 'name1', id: 'id1' }, { name: 'name2', id: 'id2' }, { name: 'name3', id: 'id3' }, { name: 'name4', id: 'id4' }, { name: 'name5', id: 'id5' }, { name: 'name6', id: 'id6' }, { name: 'name7', id: 'id7' }, { name: 'name8', id: 'id8' }, ]


function split(data,...strs){
  let res = [];
  let last = 0;
  strs.forEach((x,i) => {
    let index = data.findIndex(a => a.id === x);
    res.push(data.slice(last,index));
    last = index;
  })
  return res.concat([data.slice(last)])
}

let result = split(data,"id3","id6")

const [first,second,third] = result;


console.log('First:',first);
console.log('Second:',second);
console.log('Third:',third);

如果要基于id进行此操作,可以先使用findIndex,然后再使用slice()

答案 1 :(得分:1)

const data = [
    { name: 'name1', id: 'id1' },
    { name: 'name2', id: 'id2' },
    { name: 'name3', id: 'id3' },
    { name: 'name4', id: 'id4' },
    { name: 'name5', id: 'id5' },
    { name: 'name6', id: 'id6' },
    { name: 'name7', id: 'id7' },
    { name: 'name8', id: 'id8' },
];

const firstArr = [];
const secondArr = [];
const thirdArr = [];

data.map(item => {
    if (item.id < 'id3') {
        firstArr.push(item);
    } else if (item.id > 'id5') {
        thirdArr.push(item);
    } else {
        secondArr.push(item);
    }
});

console.log(firstArr);
console.log(secondArr);
console.log(thirdArr);

答案 2 :(得分:1)

您可以使用Array.slice()Array.findIndex()

const id3Index = data.findIndex(obj => obj.id === 'id3');
const id6Index = data.findIndex(obj => obj.id === 'id6');
const arr1 = data.slice(0, id3Index);
const arr2 = data.slice(id3Index, id6Index);
const arr3 = data.slice(id6Index);

const data = [
  {
    name: 'name1',
    id: 'id1'
  },
  {
    name: 'name2',
    id: 'id2'
  },
  {
    name: 'name3',
    id: 'id3'
  },
  {
    name: 'name4',
    id: 'id4'
  },
  {
    name: 'name5',
    id: 'id5'
  },
  {
    name: 'name6',
    id: 'id6'
  },
  {
    name: 'name7',
    id: 'id7'
  },
  {
    name: 'name8',
    id: 'id8'
  },

]

const id3Index = data.findIndex(obj => obj.id === 'id3');
const id6Index = data.findIndex(obj => obj.id === 'id6');
console.log(data.slice(0, id3Index));
console.log(data.slice(id3Index, id6Index));
console.log(data.slice(id6Index));

答案 3 :(得分:1)

您可以使用findIndex()来找到id3id6,然后使用slice()并提取子数组:

const data = [{name:"name1",id:"id1"},{name:"name2",id:"id2"},{name:"name3",id:"id3"},{name:"name4",id:"id4"},{name:"name5",id:"id5"},{name:"name6",id:"id6"},{name:"name7",id:"id7"},{name:"name8",id:"id8"}];

function process(arr) {
  const id3 = arr.findIndex(({ id }) => id === 'id3');
  const id6 = arr.findIndex(({ id }) => id === 'id6');
  return [arr.slice(0, id3), arr.slice(id3, id6), arr.slice(id6)];
}

const [arr1, arr2, arr3] = process(data);

console.log(JSON.stringify(arr1));
console.log(JSON.stringify(arr2));
console.log(JSON.stringify(arr3));

答案 4 :(得分:0)

我会使用像这样的reducer函数

console.clear()
const data = [
  {name: "name1", id: "id1"},
  {name: "name2", id: "id2"},
  {name: "name3", id: "id3"},
  {name: "name4", id: "id4"},
  {name: "name5", id: "id5"},
  {name: "name6", id: "id6"},
  {name: "name7", id: "id7"},
  {name: "name8", id: "id8"}
];


// start and end are arrays, which contain triggers
// start will activate, end
// id is the key to check, defaults to 'id'
const reducerId = (activate, deactivate, key) => {
  key = key || 'id'
  let use = false
  return (item, index) => {
    if (activate.length === 0 && index === 0 || activate.includes(item[key])) {
      use = true
    }
    if (deactivate.includes(item[key])) {
      use = false
    }
    return use;
  }
}

// arr is the array to split
// use is a callback, which must return true or false, depending on whether the 
// currentItem should be used in the accumulated result array or not
const splitId = (arr, use) => {
  let found = false;
  return arr.reduce((accu, item, index, source) => {
    if (use(item, index)) {
      accu.push(item)
    }
    return accu
  }, [])
}


const first = splitId(data, reducerId([], ['id3']));
const second = splitId(data, reducerId(['id3'], ['id6']));
const third = splitId(data, reducerId(['id6'], []));
console.log(JSON.stringify(first))
console.log(JSON.stringify(second))
console.log(JSON.stringify(third))

答案 5 :(得分:0)

您可以使用reduce

  • 这里的想法是第一类ID
  • 现在循环遍历已排序的数据,一旦找到任何匹配的id,便将其推送到最终输出,并从rangereset temp中删除该元素

const data = [{ name: 'name1', id: 'id1' },{ name: 'name2', id: 'id2' },{ name: 'name3', id: 'id3' },{ name: 'name4', id: 'id4' },{ name: 'name5', id: 'id5' },{ name: 'name6', id: 'id6' },{ name: 'name7', id: 'id7' },{ name: 'name8', id: 'id8' },];

let range = ['id3','id6','id9']
let temp = []
let op = data.sort(({id:a,id:b}) => a.localeCompare(b)).reduce((op,inp)=>{
  temp.push(inp)
  if(inp.id === range[0]){
    op.push(temp)
    temp = []
    range.shift()
  }
  return op
},[])
if(temp.length){
  op.push(temp)
}
console.log(op)

答案 6 :(得分:0)

您可以为id值获取一个数组,如果知道id,则可以获取一个新数组。

const
    data = [{ name: 'name1', id: 'id1' }, { name: 'name2', id: 'id2' }, { name: 'name3', id: 'id3' }, { name: 'name4', id: 'id4' }, { name: 'name5', id: 'id5' }, { name: 'name6', id: 'id6' }, { name: 'name7', id: 'id7' }, { name: 'name8', id: 'id8' }],
    groups = ['id3', 'id6'],
    [one, two, three] = data.reduce((r, o) => {
        if (o.id === groups[0]) {
            r.push([]);
            groups.shift();
        }
        r[r.length - 1].push(o);
        return r;
    }, [[]]);

console.log(one);
console.log(two);
console.log(three);
.as-console-wrapper { max-height: 100% !important; top: 0; }