在lodash上使用过滤器

时间:2015-10-30 21:15:20

标签: json lodash

我有这个JSON字符串

[
  {
    uri : '/someuri/one',
    title : 'Title 1',
    displayLocation : 'ACTION_MENU',
    masterData : 'LOCATION',
    iconClass : 'icon-class-1'
  }, 
  {
    uri : '/someuri/two',
    title : 'Title 2',
    displayLocation : 'ACTION_MENU',
    masterData : 'LOCATION',
    iconClass : 'icon-class-2'
  },
  {
    uri : '/someuri/three',
    title : 'Title 3',
    displayLocation : 'ACTION_MENU',
    masterData : 'JOB',
    iconClass : 'icon-class-3'
  },
  {
    uri : '/someuri/four',
    title : 'Title 4',
    displayLocation : 'SUMMARY',
    masterData : 'LOCATION',
    iconClass : 'icon-class-4'
  }
]

我正在将其转换为

[
  {
    iconClass : 'icon-class-1',
    id : 'anythingUnique',
    text : 'Title 1'
  }, 
  {
    iconClass : 'icon-class-2',
    id : 'anythingUnique',
    text : 'Title 2'
  }
]     

使用以下代码

function myCustomFilter(inputJSONStr) {
  return _.each(inputJSONStr.filter(function(action){
    return action.masterData === 'LOCATION' && action.displayLocation === 'ACTION_MENU';
  }), function (action) {
    return [{iconClass: action.iconClass, id: 'anythingUnique', text: action.title}];
});

但是它返回了我的JSON字符串

[
  {
    uri : '/someuri/one',
    title : 'Title 1',
    displayLocation : 'ACTION_MENU',
    masterData : 'LOCATION',
    iconClass : 'icon-class-1'
  },
  {
    uri : '/someuri/two',
    title : 'Title 2',
    displayLocation : 'ACTION_MENU',
    masterData : 'LOCATION',
    iconClass : 'icon-class-2'
  }
]

任何人都可以建议我做错了吗?

1 个答案:

答案 0 :(得分:1)

You could use map to do this:

_(inputJSONStr).filter({masterData: 'LOCATION', displayLocation: 'ACTION_MENU'})
     .map(function(a) {
         return {iconClass: a.iconClass, id: 'anythingUnique', text: a.title};
     }).value();

I've changed your filter a little, but you could do it your way if you wanted, and I've used a functional approach with chaining, but you could do it imperatively if that makes you more comfortable. Map effectively replaces an array element with the returned element.