如何从Object中删除某些键值对

时间:2017-11-23 12:01:37

标签: javascript lodash

我已经使用Lodash来到这个我需要按ID分组的结构。

分组工作正常,但我想通过字段添加更多属性,如字段名称和域,从嵌套对象,我该怎么做。

额外 - 此外,如果我需要过滤嵌套对象内的内容,如使用状态或发布者名称,我该如何添加。 Javascript的新功能

 let result = _.chain(value)
      .groupBy('pubId')
      .pairs()
      .map(function(currentItem) {
        return _.object(_.zip(['publisherId', 'targetting'], currentItem));
      })
      .value();

返回的数据

{
      "publisherId": "17",
       // add name , domain , here
      "targetting": [
        {
          "id": 1,
          "pubId": 17, // remove this
          "type": 18,
          "value": "google.com,yahoo.com",
          "status": 12,
          "createTs": null, // remove this
          "updateTs": null,// remove this
          "createUser": null,// remove this
          "updateUser": null,// remove this
          "percentage": 0,// remove this
          "rtbSspPublishers": { // remove this
            "id": 17,
            "name": "Tom's Hardware",
            "domain": "www.tomshardware.com",
            "extPublisherId": 17
          }
        },
        {
          "id": 2,
          "pubId": 17,
          "type": 14,
          "value": "Sports,Fashion",
          "status": 12,
          "createTs": null,
          "updateTs": null,
          "createUser": null,
          "updateUser": null,
          "percentage": 0,
          "rtbSspPublishers": {
            "id": 17,
            "name": "Tom's Hardware",
            "domain": "www.tomshardware.com",
            "extPublisherId": 17
          }
        },
        {
          "id": 3,
          "pubId": 17,
          "type": 11,
          "value": "Sports,Fashion",
          "status": 12,
          "createTs": null,
          "updateTs": null,
          "createUser": null,
          "updateUser": null,
          "percentage": 0,
          "rtbSspPublishers": {
            "id": 17,
            "name": "Tom's Hardware",
            "domain": "www.tomshardware.com",
            "extPublisherId": 17
          }
        }
      ]
    }

我需要从嵌套分组中删除某些属性我如何使用lodash实现使用lodash 3.0.0。请帮助谢谢

1 个答案:

答案 0 :(得分:0)

再次迭代result删除那些不需要的属性。

例如

var propsToBeDeleted = [ "createTs", "updateTs" ]; //array of properties to be deleted
result = result.map( function(item){
   propsToBeDeleted.forEach( function(prop){
      delete item[prop];
   }); 
   return item;
});

或者尝试将您的lodash代码更新为

let result = _.chain(value)
  .groupBy('pubId')
  .pairs()
  .map(function(currentItem) {
     var item =  _.object(_.zip(['publisherId', 'targetting'], currentItem));
     propsToBeDeleted.forEach( function(prop){
        delete item[prop];
     }); 
    return item;
  })
  .value();