如何从特定索引中遍历对象数组

问题描述 投票:0回答:3

我有一个test array和一个test object。我想将test array的每个元素与test object进行比较,但只比较test objecttest array之后的那些元素。

我已经通过以下示例完成了此操作。我们有任何优雅的方法来做到这一点吗?

let testArray = [{ id: xx, name: 'C' },
    { id: xy, name: 'B' },
    { id: yz, name: 'C' },
    { id: ab, name: 'D' },
    { id: bc, name: 'E' },
    { id: cd, name: 'C' },
    { id: ce, name: 'E' },
    { id: ef, name: 'C' }];

let testObj = { id: 3, name: 'C' };

for (let i = testArray.indexOf(testObj) + 1; i < testArray.length; i++) {
  if (testObj.name === testArray[i].name) {
    console.log(testArray[i].id); // expected - object with id : cd and ef
    // if I change test object to { id: cd, name: 'C' } then answer should be object with id : ef
  }
}
javascript
3个回答
2
投票

您可以这样做:

testArray.filter(i => i.id > testObj.id).forEach(i => console.log(i))

仅一行用于过滤,并显示所有已过滤的项目。


0
投票

以下解决方案将在遇到id的位置寻找索引,然后从该位置循环在目标数组上。

优雅的方式是高度主观的思想。我们都会为您提供alternative语法。应用最适合您的需求并与您的常规编码样式相匹配的一种。

const testArray = [{
    id: 1,
    name: 'C',
  },
  {
    id: 2,
    name: 'B',
  },
  {
    id: 3,
    name: 'C',
  },
  {
    id: 4,
    name: 'D',
  },
  {
    id: 5,
    name: 'E',
  },
  {
    id: 6,
    name: 'C',
  },
  {
    id: 7,
    name: 'E',
  },
  {
    id: 8,
    name: 'C',
  },
];

const testObj = {
  id: 3,
  name: 'C',
};

// Find where to start
const pos = testArray.findIndex(x => x.id === testObj.id);

// Cut the array where you want to start looking and loop on it
testArray.slice(pos).forEach(({
  id,
  name,
}) => {
  if (name === testObj.name) {
    console.log(id);
  }
});

0
投票

您可以使用.findIndex()在数组中找到对象。您可以使用.slice()将选择范围缩小到索引较高的项目,然后使用filter()来获得仅具有匹配名称的项目。

let testArray = [{ id: 1, name: 'C' },{ id: 2, name: 'B' },{ id: 3, name: 'C' },{ id: 4, name: 'D' },{ id: 5, name: 'E' },{ id: 6, name: 'C' },{ id: 7, name: 'E' },{ id: 8, name: 'C' }];
let testObj = { id: 3, name: 'C' };

const getItemsAfterObj = (arr, obj) => {
  const idx = arr.findIndex(o => o.id === obj.id && o.name === obj.name);
  if (idx === -1) throw "Object not found in array.";
  return arr.slice(idx+1).filter(o => o.name === obj.name);
};

const items = getItemsAfterObj(testArray,testObj); //Get the items
items.forEach(({id}) => console.log(id));          //Log the IDs
© www.soinside.com 2019 - 2024. All rights reserved.