我有两个 javascript JSON 数组如下:
this.BicyclePartsOLD;
this.BicyclePartsNEW;
所以基本上两者都有一个属性“ListOrder”。 OLD 由 ListOrder 从 1 到 n 项排序。
NEW 已修改但与 BicyclePartsOLD 具有相同的记录,因此 OLD 需要从 NEW 更新。如果有人在 NEW 中将 ListOrder
从 1 更改为 3,我需要更新 OLD 列表以将该值设为 3,并使 ListOrder 2 = 1,ListOrder 3 = 2。
我正在尝试通过以下方式进行操作,但我一直坚持将 ListOrder 设置为新数字的最佳方式:
for(var i = 0; i < this.BicyclePartsOLD.length; i++)
{
for(var j = 0; j < this.BicyclePartsNEW.length; j++)
{
if(this.BicyclePartsOLD[i].PartNumber === this.BicyclePartsNEW[j].PartNumber)
{
this.BicyclePartsOLD[i].ListOrder = this.BicyclePartsNEW[j].ListOrder;
//NOT Sure how to reorder BicyclePartsOLD here, there will be another
//item with the same ListOrder at this point.
}
}
}
任何能引导我走向正确方向的建议都将不胜感激。
最佳答案
跳出框框思考,与其拥有 2 个具有相同数据但在对象方面完全不相关的数组,为什么不创建 2 个数组,它们都包含相同的对象?这样,编辑一个对象就好像您在两个地方都在编辑它一样。
首先,you can have 2 arrays but both point to the same objects :
Array1 -> [{foo:'bar'},{baz:'bam'}]
Array2 -> [{baz:'bam'},{foo:'bar'}]
第一个数组中带有 foo
的对象可以与另一个数组中带有 foo
的对象完全相同(我的意思是相同 对象实例,不仅仅是因为它们具有相同的属性)。所以编辑一个基本上看起来好像它们在两个地方都发生了变化。
所以有了这个概念,你可以做一个 slice()
在新阵列上给你一个 1-level copy of the array .基本上,它是不同数组容器中完全相同的项目。然后你可以 sort
新切片的数组,但是你想要它。
this.BicyclePartsOLD = this.BicyclePartsNEW.slice().sort(function(){...});
现在,为了避免像我的第一个解决方案那样重复切片,我建议您先创建 OLD 和 NEW 数组。然后,当您添加一个条目时,使用您的数据创建一个对象,并将该对象推送到两个数组,这样两个数组都包含相同的对象,编辑它会反射(reflect)在两个数组上。
var OLD = [];
var NEW = [];
// Adding an entry
var newItem = {}
OLD.push(newItem);
NEW.push(newItem);
//Editing that item should reflect on both arrays, since they're the same
OLD[0].someProperty = 'someValue';
console.log(OLD[0].someProperty); // someValue
console.log(NEW[0].someProperty); // someValue
// An item only on OLD
var oldItem = {};
OLD.push(oldItem);
// An item only on OLD
var yetAnotherOldItem = {};
OLD.push(yetAnotherOldItem);
// Let's bring one of those old items to NEW and edit it
NEW.push(OLD[2]);
OLD[2].revived = 'I feel new!';
// Should be in both arrays, but in different indices (since there's the second OLD item)
console.log(OLD[2].revived); // someValue
console.log(NEW[1].revived); // someValue
关于javascript - 比较两个 json 数组并更改位置的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20895791/