我有2个对象数组.每个对象都有一个Id属性.现在,如果我有一个只有Ids的第三个数组,那么基于这些ID并将它们移动到array2,从array1中查找对象的更好更快的方法是什么.
非常感谢您的回答..
示例代码:
Person = function(id, fn, ln) {
this.id = id,
this.firstName = fn,
this.lastName = ln
}
array1 = new Array();
// add 500 new Person objects to this array
array2 = new Array();
// add some other new Person objects to this array
function moveArrayItems(ids) {
// ids is an array of ids e.g. [1,2,3,4,5,6,...]
// Now I want to find all the person objects from array1 whose ids
// match with the ids array passed into this method. Then move them to array2.
// What is the best way to achive this?
}
Run Code Online (Sandbox Code Playgroud)
如果你真的在每个数组中有500多个对象,你可能最好使用哈希来存储对象,用id键入:
var people = {
1: {id:1, name:"George Washington"},
2: {id:2, name:"John Adams"},
3: {id:3, name:"Thomas Jefferson"}, // ...
}
var people2 = {}
Run Code Online (Sandbox Code Playgroud)
现在通过ID移动东西是微不足道的(并且更快,更快):
function moveArrayItems(ids) {
var i,id;
for (i=0; i<ids.length; i++){
id = ids[i];
if (people1[id]) {
people2[id] = people1[id];
delete people1[id];
}
}
}
Run Code Online (Sandbox Code Playgroud)