在lodash组合中需要帮助才能获得以下对象

时间:2015-09-02 13:01:50

标签: javascript lodash

下面是我的对象第一步是检查socialAuth对象数组并获取具有showStats值为false的platformName。     我已经完成了以下步骤1

var arrList2 = _.pluck(_.where(creatorObj.socialAuth, {'showStats': false}), "platformName");

['Twitter'] is the output of the arrList2

var creatorObj = 
{
  "_id": "55e5b32f3874c964cc3dfe2e",
  "firstName": "xyz",
  "lastName": "abc",
  "socialStats": [
    {
      "reach": 205976,
      "_id": "asdfasdfasdf",
      "profileUrl": null,
      "engagements": 126,
      "platformName": "Twitter"
    }
  ],
  "socialAuth": [
    {
      "screenName": "abc",
      "userId": "12341234",
      "_id": "55e5b3573874c964cc3dfe33",
      "showStats": false,
      "platformName": "Twitter"
    },
    {
      "channelTitle": "xyz",
      "channelId": "sdfgsdfgsdfg",
      "_id": "55e5a040991c1321a5b9bd79",
      "showStats": true,
      "platformName": "Youtube"
    }
  ]
};

第二步是使用sociaStats数组检查上面的arrList2并从中删除该值并再次打印该对象。  我在第二步需要帮助。
我需要生成的对象为

var creatorObj = 
{
  "_id": "55e5b32f3874c964cc3dfe2e",
  "firstName": "xyz",
  "lastName": "abc",
  "socialStats": [],
  "socialAuth": [
    {
      "screenName": "abc",
      "userId": "12341234",
      "_id": "55e5b3573874c964cc3dfe33",
      "showStats": false,
      "platformName": "Twitter"
    },
    {
      "channelTitle": "xyz",
      "channelId": "sdfgsdfgsdfg",
      "_id": "55e5a040991c1321a5b9bd79",
      "showStats": true,
      "platformName": "Youtube"
    }
  ]
};

1 个答案:

答案 0 :(得分:1)

您需要使用_.remove()根据条件从数组中删除元素。

Demo



var creatorObj = {
  "_id": "55e5b32f3874c964cc3dfe2e",
  "firstName": "xyz",
  "lastName": "abc",
  "socialStats": [{
    "reach": 205976,
    "_id": "asdfasdfasdf",
    "profileUrl": null,
    "engagements": 126,
    "platformName": "Twitter"
  }],
  "socialAuth": [{
    "screenName": "abc",
    "userId": "12341234",
    "_id": "55e5b3573874c964cc3dfe33",
    "showStats": false,
    "platformName": "Twitter"
  }, {
    "channelTitle": "xyz",
    "channelId": "sdfgsdfgsdfg",
    "_id": "55e5a040991c1321a5b9bd79",
    "showStats": true,
    "platformName": "Youtube"
  }]
};

var arrList2 = _.pluck(_.where(creatorObj.socialAuth, {
  'showStats': false
}), "platformName");

creatorObj.socialStats = _.remove(creatorObj.socialStats, function(n) {
  return !_.includes(arrList2, n.platformName);
});


console.log(creatorObj);
document.write(JSON.stringify(creatorObj));

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
&#13;
&#13;
&#13;