如果两个以下对象具有不同的值,如何修改对象数组?
考虑此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
如果它具有orde> 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)
你有什么想法吗?谢谢
Consider this 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
is always sorted by order
.
I want to modify it to get:
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
must be inserted into an object if it has an order
different from the preceding object.
I'm unable to write this function, even if it might be quite simple (I guess!).
At this time, I have this, but it doesn't work at all and I don't understand its behavior.
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)
Do you have any idea? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以映射一个新数组并检查项目和前任。
You could map a new array and check the item and the predecessor.
试试这个
Try this
现有阵列的最简单更改
Simplest change of existing array
更改原始数组:
Changes original array:
以下是达到您想要的相同结果的另一种方法。
我相信一种更通用的方式。
Below is another way to achieve the same result as you want.
I believe a more generalized way.
continue
You can copy the array:
Shift it (so the first item is the second one!)
Loop over both