Remove Object from Array using JavaScript

前端 未结 29 2566
南笙
南笙 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:40

    I have made a dynamic function takes the objects Array, Key and value and returns the same array after removing the desired object:

    function removeFunction (myObjects,prop,valu)
            {
                 return myObjects.filter(function (val) {
                  return val[prop] !== valu;
              });
    
            }
    

    Full Example: DEMO

    var obj = {
                "results": [
                  {
                      "id": "460",
                      "name": "Widget 1",
                      "loc": "Shed"
                  }, {
                      "id": "461",
                      "name": "Widget 2",
                      "loc": "Kitchen"
                  }, {
                      "id": "462",
                      "name": "Widget 3",
                      "loc": "bath"
                  }
                ]
                };
    
    
            function removeFunction (myObjects,prop,valu)
            {
                 return myObjects.filter(function (val) {
                  return val[prop] !== valu;
              });
    
            }
    
    
    console.log(removeFunction(obj.results,"id","460"));
    

提交回复
热议问题