Lodash:仅过滤所需的属性

时间:2017-05-11 08:30:11

标签: javascript angularjs lodash

 [
  {
    "Office_Id": 100,
    "Address1": "xxxxx",
    "Address2": "",
    "City": "ANNISTON",
    "District_Id": 1277,
    "OfficeName": "test"
  },
  {
    "Office_Id": 200,
     "Address1": "xxxxx",
    "Address2": "",
    "City": "ANNISTON",
    "District_Id": 1277,
    "OfficeName": "test"
  },
  {
    "Office_Id": 300,
     "Address1": "xxxxx",
    "Address2": "",
    "City": "ANNISTON",
    "District_Id": 1277,
    "OfficeName": "test"
  }
]

如何仅使用Office_Id和OfficeName

进行过滤

1 个答案:

答案 0 :(得分:0)

没有lodash(普通 javascript),就像这样:
(如果要删除除两个属性之外的所有内容)



let list = [
  {
    "Office_Id": 100,
    "Address1": "xxxxx",
    "Address2": "",
    "City": "ANNISTON",
    "District_Id": 1277,
    "OfficeName": "test"
  },
  {
    "Office_Id": 200,
     "Address1": "xxxxx",
    "Address2": "",
    "City": "ANNISTON",
    "District_Id": 1277,
    "OfficeName": "test"
  },
  {
    "Office_Id": 300,
     "Address1": "xxxxx",
    "Address2": "",
    "City": "ANNISTON",
    "District_Id": 1277,
    "OfficeName": "test"
  }
];

let newList = list.map(function(currentItem){
    return {"Office_Id": currentItem.Office_Id, "OfficeName": currentItem.OfficeName};
});
console.info(newList);

// Tested on Win7 64bit Chrome 57+




  

Array Object的map函数将创建一个新的Array,其中函数返回的值为过去(在本例中为x => {return {"Office_Id": x.Office_Id, "OfficeName": x.OfficeName};})。有关该功能的详细信息,请访问MDN Reference

作为注释中的状态,您可以使用lambda函数,解构和优化的文字符号来最小化代码。 (但在使用每个功能之前检查兼容性,新闻javascript版本支持

这里有一个简短的版本:
list.map(({Office_Id, OfficeName}) => ({Office_Id, OfficeName})});

更新,使用lodash:



let list = [
      {
        "Office_Id": 100,
        "Address1": "xxxxx",
        "Address2": "",
        "City": "ANNISTON",
        "District_Id": 1277,
        "OfficeName": "test"
      },
      {
        "Office_Id": 200,
         "Address1": "xxxxx",
        "Address2": "",
        "City": "ANNISTON",
        "District_Id": 1277,
        "OfficeName": "test"
      },
      {
        "Office_Id": 300,
         "Address1": "xxxxx",
        "Address2": "",
        "City": "ANNISTON",
        "District_Id": 1277,
        "OfficeName": "test"
      }
    ];


let newList = _.map(list, function(value){
  return { "Office_Id": value.Office_Id,"OfficeName": value.OfficeName};
});

console.info(newList);

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

这里是link to the Documentation of the lodash map function