如果以下两个对象具有不同的值,如何修改对象数组?

How to modify an array of objects if two following objects have different value?

考虑这个 array:

const arr = [
  {order: 1, mess:"test1"},
  {order: 2, mess:"test2"},
  {order: 2, mess:"test2"},
  {order: 2, mess:"test2"},
  {order: 3, mess:"test3"},
  {order: 4, mess:"test4"},
]

arr 总是按 order.

排序

我想修改得到:

const arr = [
  {order: 1, mess:"test1"},

  {order: 2, mess:"test2", sep:true},
  {order: 2, mess:"test2"},
  {order: 2, mess:"test2"},

  {order: 3, mess:"test3", sep:true},

  {order: 4, mess:"test4", sep:true},
]

sep 必须插入一个对象,如果它有一个 order 不同于前面的对象。

我无法编写此函数,即使它可能非常简单(我猜!)。
这时,我有了这个,但它根本不起作用,我不明白它的行为。

const arr = [
  {order: 1, mess: "test1"},
  {order: 2, mess: "test2"},
  {order: 2, mess: "test2"},
  {order: 2, mess: "test2"},
  {order: 3, mess: "test3"},
  {order: 4, mess: "test4"},
  ]


arr.forEach(function(value, i) {
  i = Number(i)
  const y = i + 1
  if (arr[i] !== undefined && arr[y] !== undefined) {
    if (arr[i].order === arr[y].order) arr[y].sep = true;
  }
});

console.log(arr)

你有什么想法吗?谢谢

您可以映射一个新数组并检查项目和前导。

const
    data = [{ order: 1, mess: "test1" }, { order: 2, mess: "test2" }, { order: 2, mess: "test2" }, { order: 2, mess: "test2" }, { order: 3, mess: "test3" }, { order: 4, mess: "test4" }],
    result = data.map((o, i, a) => i && a[i - 1].order !== o.order
        ? { ...o, sep: true }
        : o
    );

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

可以复制数组:

let arr2 = [...arr];

移动它(所以第一项是第二项!)

arr2.shift()

循环遍历两者

const arr = [{ order: 1, mess: "test1" }, { order: 2, mess: "test2" }, { order: 2, mess: "test2" }, { order: 2, mess: "test2" }, { order: 3, mess: "test3" }, { order: 4, mess: "test4" }];
let arr2 = [...arr];
arr2.shift();
const result = [arr[0]];
let sep = true;
for (const [v1, v2] of [arr, arr2]) if (v1.order===v2.order) result.push(v2); else result.push({...v2, sep})
console.log(result)

现有数组的最简单更改

const arr = [{ order: 1, mess: "test1" }, { order: 2, mess: "test2" }, { order: 2, mess: "test2" }, { order: 2, mess: "test2" }, { order: 3, mess: "test3" }, { order: 4, mess: "test4" }];

arr.forEach((value, i) => {
  if (i && arr[i-1].order !== arr[i].order) arr[i].sep = true;
});
console.log(arr)

试试这个

const arr = [
  {order: 1, mess: "test1"},
  {order: 2, mess: "test2"},
  {order: 2, mess: "test2"},
  {order: 2, mess: "test2"},
  {order: 3, mess: "test3"},
  {order: 4, mess: "test4"},
  ]

arr.forEach((obj,index)=>{
  if(index>0 && obj.order != arr[index-1]['order']){
    arr[index]['sep']=true
  }
});
console.log(arr)

更改原始数组:

arr.forEach((el, idx) => {
  if (idx === 0) {
    el.sep = true;
  } else {
    if (el.order !== arr[idx-1].order) {
      el.sep = true;
    }
  }
})

下面是实现您想要的相同结果的另一种方法。

我相信更通用的方式。

arr.forEach((obj, index) => {
  
  if(JSON.stringify(obj[index+1]) === JSON.stringify(obj[index+2])) {
    obj[index].sep = true;
  }
})