Javascript Object push() function

后端 未结 7 2105
借酒劲吻你
借酒劲吻你 2020-11-28 02:35

I have a javascript object (I actually get the data through an ajax request):

var data = {};

I have added some stuff into it:



        
相关标签:
7条回答
  • 2020-11-28 03:12

    push() is for arrays, not objects, so use the right data structure.

    var data = [];
    // ...
    data[0] = { "ID": "1", "Status": "Valid" };
    data[1] = { "ID": "2", "Status": "Invalid" };
    // ...
    var tempData = [];
    for ( var index=0; index<data.length; index++ ) {
        if ( data[index].Status == "Valid" ) {
            tempData.push( data );
        }
    }
    data = tempData;
    
    0 讨论(0)
  • 2020-11-28 03:21

    I assume that REALLY you get object from server and want to get object on output

    Object.keys(data).map(k=> data[k].Status=='Invalid' && delete data[k])
    

    var data = { 5: { "ID": "0", "Status": "Valid" } }; // some OBJECT from server response
    
    data = { ...data,
      0: { "ID": "1", "Status": "Valid" },
      1: { "ID": "2", "Status": "Invalid" },
      2: { "ID": "3", "Status": "Valid" }
    }
    
    // solution 1: where output is sorted filtred array
    let arr=Object.keys(data).filter(k=> data[k].Status!='Invalid').map(k=>data[k]).sort((a,b)=>+a.ID-b.ID);
      
    // solution2: where output is filtered object
    Object.keys(data).map(k=> data[k].Status=='Invalid' && delete data[k])
      
    // show
    console.log('Object',data);
    console.log('Array ',arr);

    0 讨论(0)
  • 2020-11-28 03:26

    You must make var tempData = new Array();

    Push is an Array function.

    0 讨论(0)
  • 2020-11-28 03:28
        tempData.push( data[index] );
    

    I agree with the correct answer above, but.... your still not giving the index value for the data that you want to add to tempData. Without the [index] value the whole array will be added.

    0 讨论(0)
  • 2020-11-28 03:29

    Objects does not support push property, but you can save it as well using the index as key,

    var tempData = {};
    for ( var index in data ) {
      if ( data[index].Status == "Valid" ) { 
        tempData[index] = data; 
      } 
     }
    data = tempData;

    I think this is easier if remove the object if its status is invalid, by doing.

    for(var index in data){
      if(data[index].Status == "Invalid"){ 
        delete data[index]; 
      } 
    }

    And finally you don't need to create a var temp –

    0 讨论(0)
  • 2020-11-28 03:35

    Do :

    
    var data = new Array();
    var tempData = new Array();
    
    
    0 讨论(0)
提交回复
热议问题