这是我的第一个数组的结构:
var myArray = [1,Firstname,Lastname];
我的第二个数组由具有属性的对象组成:
var mySecondArray = [object, object, object];
当你展开它时,在第一个数组对象上它将显示如下内容:
Id = 1
FirstName = Test
LastName = TestLastName
如果对象与第一个数组具有相同的id
,则需要删除该对象。我试过用这个但没有运气:
// if condition
myArray.splice(mySecondArray[x].ID, 1);
有什么想法吗?
修改
所以这就是整个想法。我有所有项目(对象)的数组,我有无效项目数组(在这种情况下,这是字符串数组)
var originalLength = validRowsArray.length;
for (var x = 0; x < invalidRowsArray.length; x++) {
for (var y = 0; y < originalLength; y++) {
if (validRowsArray[x].ID != invalidRowsArray[y][0]) { // 0 is the position of ID
validRowsArray.splice(validRowsArray[x], 1);
}
}
}
答案 0 :(得分:1)
您正在使用第二个数组中对象的属性作为要拼接的对象的参数:
myArray.splice(mySecondArray[x].ID, 1);
但是您应该传递给splice
的第一个参数是要在其包含数组中删除的对象的索引。
在伪代码中,您的算法应该这样做:
for each item in array_a
look for a match in array b
determine the index of the matching object in array b
splice one item at that index from array b
答案 1 :(得分:1)
if (!test[0].childNodes || !test[0].childNodes.length ||
!test[0].childNodes[0].nodeValue) {
test1 =test[0].childNodes ="";
}else{
test1 =test[0].childNodes[0].nodeValue;
}
可以是任何值,与myArray.splice(mySecondArray[x].ID, 1);
假设您知道索引并且splice()
只是使用
x
目前尚不清楚您如何定义myArray.splice(x, 1);
答案 2 :(得分:1)
我认为你可以使用拼接,导致不是2个数组,是一个对象和一个数组所以,这里你有答案,但是当没有包含数组时,只需在最后添加它,否则只需替换rigth ?,测试一下:
var myArray = [1,Firstname,Lastname]; //array user*
var mySecondArray = [object, object, object]; //array with objects(user)
Array.prototype.insertArray = function ( myArray ){
var addMyArray = true;
for(var i=0; i<this.length; i++){
//compare 2 Id's
if(this[i].Id == myArray[0]){ //if equals -> replace
this[i].FirstName = myArray[1];
this[i].LastName = myArray[2];
addMyArray = false;
}
}
//in case you array is not in your 'secondarray' it should be added right?
if(addMyArray){
this.push( {Id:myArray[0], FirstName:myArray[1], LastName:myArray[2]} );
}
}
//Note: call your function after write prototype always
mySecondArray.insertArray( myArray );
//check right answer :)
console.log(mySecondArray)
答案 3 :(得分:1)
使用反向for
循环确保在删除时不会遗漏元素。
然后使用some
检查当前元素是否存在于无效数组中。
splice使用索引作为第一个参数,然后计为第二个。
var invalidRowsArray = [
[2, 'foo2', 'bar2']
];
var validRowsArray = [{
Id: 1,
FirstName: 'foo',
LastName: 'bar'
}, {
Id: 2,
FirstName: 'foo2',
LastName: 'bar2'
}, {
Id: 3,
FirstName: 'foo3',
LastName: 'bar3'
}];
for (var i = validRowsArray.length; i--;) {
var exist = invalidRowsArray.some(function(element) {
return element[0] == validRowsArray[i].Id;
})
if (exist)
validRowsArray.splice(i, 1)
}
console.log(validRowsArray);
&#13;
答案 4 :(得分:0)
正如你所说,'如果第一个数组中的id具有相同的id,我需要删除该对象'第一个数组是否只包含数字? 无论如何,如果你想从第二个数组中删除对象而你有索引,你可以这样做,
delete mySecondArray[x]
as myarray [x] == mySecondArray [x] .Id working fiddle