Remove Object from Array using JavaScript

前端 未结 29 2054
南笙
南笙 2020-11-22 10:24

How can I remove an object from an array? I wish to remove the object that includes name Kristian from someArray. For example:

som         


        
相关标签:
29条回答
  • 2020-11-22 10:49

    I guess the answers are very branched and knotted.

    You can use the following path to remove an array object that matches the object given in the modern JavaScript jargon.

    
    coordinates = [
        { lat: 36.779098444109145, lng: 34.57202827508546 },
        { lat: 36.778754712956506, lng: 34.56898128564454 },
        { lat: 36.777414146732426, lng: 34.57179224069215 }
    ];
    
    coordinate = { lat: 36.779098444109145, lng: 34.57202827508546 };
    
    removeCoordinate(coordinate: Coordinate): Coordinate {
        const found = this.coordinates.find((coordinate) => coordinate == coordinate);
        if (found) {
          this.coordinates.splice(found, 1);
        }
        return coordinate;
      }
    
    0 讨论(0)
  • 2020-11-22 10:50

    splice(i, 1) where i is the incremental index of the array will remove the object. But remember splice will also reset the array length so watch out for 'undefined'. Using your example, if you remove 'Kristian', then in the next execution within the loop, i will be 2 but someArray will be a length of 1, therefore if you try to remove "John" you will get an "undefined" error. One solution to this albeit not elegant is to have separate counter to keep track of index of the element to be removed.

    0 讨论(0)
  • 2020-11-22 10:50

    Here is an example with map and splice

    const arrayObject = [
      { name: "name1", value: "value1" },
      { name: "name2", value: "value2" },
      { name: "name3", value: "value3" },
    ];
    
    let index = arrayObject.map((item) => item.name).indexOf("name1");
    if (index > -1) {
      
      arrayObject.splice(index, 1);
      console.log("Result", arrayObject);
      
    
    }

    0 讨论(0)
  • 2020-11-22 10:51

    You could also try doing something like this:

    var myArray = [{'name': 'test'}, {'name':'test2'}];
    var myObject = {'name': 'test'};
    myArray.splice(myArray.indexOf(myObject),1);
    
    0 讨论(0)
  • 2020-11-22 10:52

    Although this is probably not that appropriate for this situation I found out the other day that you can also use the delete keyword to remove an item from an array if you don't need to alter the size of the array e.g.

    var myArray = [1,2,3];
    
    delete myArray[1];
    
    console.log(myArray[1]); //undefined
    
    console.log(myArray.length); //3 - doesn't actually shrink the array down
    
    0 讨论(0)
  • 2020-11-22 10:53

    This is a function that works for me:

    function removeFromArray(array, value) {
        var idx = array.indexOf(value);
        if (idx !== -1) {
            array.splice(idx, 1);
        }
        return array;
    }
    
    0 讨论(0)
提交回复
热议问题