Remove property in Javascript

This question already has an answer here:

  • How do I remove a property from a JavaScript object? 33 answers

  • 您可以使用删除将其删除

    delete b[0].color
    

    If you're using .push({}) and pushing an object literal and not having reference any other way to those objects just use map:

    b = b.map(function(obj) {
      return {data: obj.data, width: obj.width};
    });
    

    If you happen to have reference then the only way I can really think of it would be to use the delete keyword even though I don't recommend it:

    for(var obj of b) {
      delete obj.color;
    }
    

    You can write a function to find all objects where they have a property and that property has a targeted values that you want to delete.

    The program is pretty self-explanatory. Add a comment if you are missing a concept.

    /* Redirect console output to HTML. */ document.body.innerHTML = '';
    console.log=function(){document.body.innerHTML+=[].slice.apply(arguments).join(' ')+'n';};
    
    var b = [{
      data: 'Red',
      width: 1,
      color: '#FF0000'
    }, {
      data: 'Blue',
      width : 1,
      color: '#00FF00'
    }, {
      data: 'Green',
      width: 1,
      color: '#0000FF'
    }];
    
    function removeProperty(items, key, value, propToRemove) {
      items.forEach(function(item) {
        if (item != null && item[key] === value) {
          delete item[propToRemove];
        }
      });
    }
    
    // delete the 'color' property of the provided data matches.
    removeProperty(b, 'data', 'Blue', 'color');
    
    console.log(JSON.stringify(b, null, '  '));
    body { font-family: monospace; white-space: pre; font-size: 11px; }
    链接地址: http://www.djcxy.com/p/4668.html

    上一篇: 有没有办法从js对象中删除整个属性

    下一篇: 删除Javascript中的属性