如何比较JSON数组并分配固定值

时间:2014-11-30 08:07:31

标签: javascript json replace insert-update lodash

我想将'apps'中所有喜欢的值更改为false,除了'favoriteList'中的那些值。我宁愿在lo-dash中这样做。

var apps = [{
    app_ID: 1,
    favorite: false
  },{
    app_ID: 2,
    favorite: false
  },{
    app_ID: 3,
    favorite: false
  },{
    app_ID: 4,
    favorite: false
  },{
    app_ID: 5,
    favorite: true
  }]


var favoriteList = [{id: 2},{id: 4}];

var updateFavorites = function(){
    _(apps).forEach(function(app){
      if (_.contains(favoriteList, app.app_ID){
        app.favorite = true;
      }else{
         app.favorite = false;
      }
    })
}

//expected outcome is all apps.app_ID values should be false except app_ID's 2 and 4.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>

2 个答案:

答案 0 :(得分:2)

我认为更好的搜索数组,所以我将favoriteList转换为数组

var favoriteList = _.map([{id: 2}, {id: 4}], 'id');

apps = _.forEach(apps, function (el) {
  el.favorite = !!~_.indexOf(favoriteList, el.app_ID);
  // or   
  // el.favorite = _.indexOf(favoriteList, el.app_ID) > -1 ? true : false;
  // this is the same, but more clearly for understanding
});

演示:http://jsbin.com/januke/1/edit?js,console

JSPerf:http://jsperf.com/seach-and-change-property-test

答案 1 :(得分:1)

我还不太熟悉lodash,但看起来你的代码并不遥远:

var updateFavorites = function(){
    _(apps).forEach(function(app){
        app.favorite = !!_.find(favoriteList, { 'id': app.app_ID }); 
    })
};

在没有结果时查找返回数组或未定义。 !是双重否定(暗示强制转换为布尔值)。所以!! undefined === false,!! [&#39; anyorevennothing&#39;] === true