0

こんにちは私は自分が持っているオブジェクト配列からオブジェクトを削除してから、別の新しいオブジェクトを作成しようとしていました($ .map()を使用して新しいオブジェクトを作成しています)

このオブジェクトをobject(x)から削除するには、そのobject.numberは、array(y)の数値の1つと一致する必要があります。

この次のコードは機能しますが、object.number =40DEMOを持つオブジェクトのみを削除し ます

コード:

   var x =[ //this is the object 
  {name : 'mark' , number : '10' , color:'green'},
  {name : 'jeff' , number : '15' , color:'blue'} ,
  {name : 'joy' , number : '30' , color:'yellow'},
  {name : 'mick' , number : '15' , color:'red'},
  {name : 'mick' , number : '40' , color:'black'}] ; 

      var y =['40','15']; // i need to remove all object.number that match the 
        // number in this array

     var newObject = $.map(x  ,function(index, value){
        for(i in y){
         if(index.number == y[i])
        {return null ; }
       else{
        return index;
            }      
      }

    });
 console.log(newObject);​

上記のコードは、object.numberに40が含まれているオブジェクトのみを削除します。これを機能させるにはどうすればよいですか?

4

5 に答える 5

0

これはあなたが望むものです:

var newObject = $.map(x  ,function(index, value){
    for(i in y){
        if(index.number == y[i])
            return null;
    }
    return index;
});
console.log(newObject);​

およびjsFiddle。ちなみに、for(i in y)配列に使用するのは良い習慣ではないと思います(配列には他のプロパティがある場合があります)。標準を使用する必要があります:

var l = y.length;
for(var i = 0; i < l; i++){
    /* the other code */
}

長さのキャッシュに注意してください。

于 2012-06-18T21:25:39.167 に答える
0

このコードを試してください:

var newObject = $.map(x, function(index, value){  
    return (y.indexOf(index.number) != -1) ? null : index;
});

http://jsfiddle.net/Dc68W/

于 2012-06-18T21:27:26.157 に答える
0

以下のように関数を変更してみてください。

var newObject = $.map(x, function(value, index) {   
   if ($.inArray(value.number, y) == -1) {
       return value;
   } else {
       return null;
   }
});

デモ:http: //jsfiddle.net/skram/C3d9T/7/

于 2012-06-18T21:27:35.897 に答える
0

以下を使用してください:

var newObject = $.map($.makeArray(x), function(index, value){  
    return y.indexOf(index.number) != -1 ? null : index;
});

$.makeArray()必須ではありませんが、配列に無秩序なデータが含まれる可能性がある場合は推奨されます。

于 2012-06-18T21:29:10.647 に答える
0

ここであなたのフィドルを更新しました。基本的に、削除配列の各値をチェックしていませんでした。

var x =[
{name : 'mark' , number : '10' , color:'green'},
{name : 'jeff' , number : '15' , color:'blue'} ,
{name : 'joy' , number : '30' , color:'yellow'},
{name : 'mick' , number : '15' , color:'red'},
{name : 'mick' , number : '40' , color:'black'}] ; 

var y =['40','15'];

var newObject = $.map(x  ,function(index, value){

    var valid = true;
    for(var i = 0; i < y.length; i++){

        if(index.number == y[i])
           valid = false;             
    }
    if(valid)return index;
    else return null;
    });
console.log(newObject);​
于 2012-06-18T21:30:31.917 に答える