我有两个javascript JSON数组,如下所示:
this.BicyclePartsOLD;
this.BicyclePartsNEW;
所以基本上两者都有一个属性“ListOrder”。 ListOrder将OLD从1个项目排序为n个项目。
新的一个被修改但与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.
}
}
}
任何可以引导我进入正确方向的建议都会非常感激。
答案 0 :(得分:2)
开箱即用,而不是让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
的完全相同的对象(我的意思是相同的对象实例,而不仅仅是因为它们具有相同的属性)。所以编辑一个基本上看起来好像在两个地方都发生了变化。
因此,使用该概念,您只需在NEW数组上执行 slice()
即可为您提供1-level copy of the array。基本上,它与不同数组容器中的完全相同。然后,您可以根据需要sort
新切片的数组。
this.BicyclePartsOLD = this.BicyclePartsNEW.slice().sort(function(){...});
现在为了避免像我的第一个解决方案那样反复切片,我建议你先创建OLD和NEW数组。然后,当您添加一个条目时,使用您的数据创建一个对象并将该对象推送到两个数组,这样两个数组都保持相同的对象,并且编辑它将反映在两个数组上。
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