如何获取没有有效字段的对象?

时间:2019-01-04 15:28:05

标签: javascript arrays ecmascript-6

我正在尝试从data中获取有效和无效的数组,我们如何使用过滤器来完成这两项操作,以提供与条件匹配的有效数组,反之亦然。

数据

   const misMatchedItems = [];
      const matchedItems = [];
       const rxInfos=  [{
                "drugName": "ATRIPLA TABS",
                "ancillaryProductInd": "false",
                "firstFillIndicator": "N",
                "indexId": "1",
                "uniqueRxId": "1711511459709"
            },
            {
                "errorDetails": {
                    "errorCode": "0077",
                    "errorDesc": "uniqueRxId not found for2711511911555"
                }
            }
        ]

    const validArray = rxInfos.filter((element) => {
                    return (element.hasOwnProperty('indexId'));
                });
    matchedItems = validArray;
    const inValidArray = rxInfos.filter((element) => {
                    return (element.hasOwnProperty(!'indexId'));
                });

    misMatchedItems = inValidArray;

2 个答案:

答案 0 :(得分:3)

您的否定(感叹号)在错误的位置。我相信这应该可行:

const inValidArray = rxInfos.filter((element) => {
            return !(element.hasOwnProperty('indexId'));
        });

您还可以一次通过两个动作:

const validArray = [];
const invalidArray = [];

rxInfos.forEach(function(element) {
   if (element.hasOwnProperty('indexId')) {
       validArray.push(element);
   } else {
       invalidArray.push(element);
   }
});

答案 1 :(得分:2)

这使用destructuring assigmentreduce来实现您的目标。

const [misMatchedItems, matchedItems] = (rxInfos.reduce((rxInfosSeparated, item) => {
  rxInfosSeparated[item.hasOwnProperty('indexId') ? 1 : 0].push(item);
  return rxInfosSeparated
}, [[] , []]));

const rxInfos=  [{
  "drugName": "ATRIPLA TABS",
  "ancillaryProductInd": "false",
  "firstFillIndicator": "N",
  "indexId": "1",
  "uniqueRxId": "1711511459709"
},
{
  "errorDetails": {
      "errorCode": "0077",
      "errorDesc": "uniqueRxId not found for 2711511911555"
  }
},
{
  "errorDetails": {
      "errorCode": "0078",
      "errorDesc": "uniqueRxId not found for 2711511911556"
  }
},
{
  "drugName": "ATRIPLA CAPSULES",
  "ancillaryProductInd": "false",
  "firstFillIndicator": "N",
  "indexId": "2",
  "uniqueRxId": "1711511459708"
}]

const [misMatchedItems, matchedItems] = (rxInfos.reduce((rxInfos, item) => {
  rxInfos[item.hasOwnProperty('indexId') ? 1 : 0].push(item);
  return rxInfos
}, [[] , []]));

console.log(misMatchedItems);
console.log(matchedItems);