【问题标题】:Compare JSON values and get new JSON比较 JSON 值并获取新的 JSON
【发布时间】:2020-02-05 09:08:49
【问题描述】:

我有以下 JSON

 [
  {
    "Key": "file/ERROR-FILE1-123.xlsx",
  },
   {
    "Key": "file/PROCESS-FILE1-123.xlsx",
  },
  {
    "Key": "file/PROCESS-FILE2-111.xlsx",
  },
  {
    "Key": "file/SUCCESS-FILE2-111.xlsx",
  },
  {
    "Key": "file/PROCESS-FILE3-121.xlsx",
  },
]

我要在这里实现的首先检查 JSON 密钥字符串的最后一部分是否相同,然后我将检查 PROCESS 和 ERROR 并显示 ERROR 文件...

例如,在我的 JSON 中,key[0] 是“file/ERROR-FILE1-123.xlsx”,key[1] 是“file/PROCESS-FILE1-123.xlsx”,所以对于 keys -FILE1-123 .xlsx 相同,因此将过滤错误文件并将其添加到新的 JSON 中。如果最后一部分相同,则与其他 JSON 相同,然后将优先考虑 SUCCESS 和 ERROR,并仅将这些文件添加到新 JSON,但如果 PROCESS 键是单一的,我的意思是没有 ERROR 或 SUCCESS 可用,那么将仅显示流程文件

所以我预期的新 JSON 应该是这样的。请帮助如何实现这一点,因为我对 UI 技术完全陌生,仍处于学习阶段。如果有更好的方法来实现这一点,请分享

 [
  {
    "Key": "file/ERROR-FILE1-123.xlsx",
  },
  {
    "Key": "file/SUCCESS-FILE2-111.xlsx",
  },
  {
    "Key": "file/PROCESS-FILE3-121.xlsx",
  },
 ]

【问题讨论】:

  • 文件的格式会一直是file/[TYPE]-FILE[NUMBER]-[NUMBER].xlsx吗?
  • 是的,它永远都是一样的
  • 是的,格式总是文件/[TYPE]-FILE[NUMBER]-[NUMBER].xlsx

标签: javascript json angular typescript


【解决方案1】:

您可以将状态与字符串分开,按文件名分组并获得优先的非进程对象。

function getParts(s) {
    return (s.match(/^(.*)(ERROR|PROCESS|SUCCESS)-(.*)$/) || []).slice(1);
}

var data = [{ Key: "errorbyte.xlsx" }, { Key: "file/ERROR-FILE1-123.xlsx" }, { Key: "file/PROCESS-FILE1-123.xlsx" }, { Key: "file/PROCESS-FILE2-111.xlsx" }, { Key: "file/SUCCESS-FILE2-111.xlsx" }, { Key: "file/PROCESS-FILE3-121.xlsx" }],
    result = Object.values(data.reduce((r, o) => {
            var [left, state, right] = getParts(o.Key),
                file = left + right;

            if (left === undefined) return r;
            if (!r[file] || r[file].state === 'PROCESS') r[file] = { o, state };
            return r;
        }, {}))
        .map(({ o }) => o);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

  • 请添加出现错误的字符串。看起来,模式不匹配。
  • 现在我正在处理动态文件所以获取这种 json 数据 [{ERROR-FILE1-2020.xlsx},{PROCESS-FILE1-2020.xlsx},{errorbyte.xlsx}, {SUCCESS-FILE2-2020.xlsx},{PROCESS-FILE2-2020.xlsx},{PROCESS-FILE3-2020.xlsx}]
  • 'errorbyte.xlsx' 是什么意思?是 ERROR 类型吗?
  • 这个文件应该被忽略,不需要在新的json中添加它
【解决方案2】:

尝试使用:

var jsonObj = [{"Key":"ERROR-FILE1-2020.xlsx"},{"Key":'PROCESS-FILE1-2020.xlsx'},{"Key":"errorbyte.xlsx"},{"Key":"SUCCESS-FILE2-2020.xlsx"},{"Key":"PROCESS-FILE2-2020.xlsx"},{"Key":"PROCESS-FILE3-2020.xlsx"}]
var obj = {};
jsonObj.forEach((elem) => {
    let file_name = elem.Key.substring(elem.Key.indexOf("-") + 1)
    let status = elem.Key.substring((elem.Key.indexOf("/") + 1), elem.Key.indexOf("-"))
    if(status!== ''){
    if (obj[file_name] === undefined) {
        
        obj[file_name] = status;
    }
    else {
        if (status === 'SUCCESS') {
            obj[file_name] = status;
            
        }
        if (status === 'ERROR') {
            if(obj[file_name] !== 'SUCCESS'){
            obj[file_name] = status;
        }
        }
    }}
    })
var result = [];
for(key in obj){ let x = {}
    x['Key'] ='file/'+obj[key]+'-'+key 
    result.push(x)
}
console.log(result)

希望对你有帮助。

【讨论】:

  • 现在我正在处理动态文件所以获取这种 json 数据 [{ERROR-FILE1-2020.xlsx},{PROCESS-FILE1-2020.xlsx},{errorbyte.xlsx}, {SUCCESS-FILE2-2020.xlsx},{PROCESS-FILE2-2020.xlsx},{PROCESS-FILE3-2020.xlsx}]
  • 这个文件应该被忽略,不需要在新的json中添加这个
【解决方案3】:

我们将在数组上循环并构建一个新数组,保留每个 Key 的代码和类型。

对于每个值,我们将检查我们正在构建的数组中的内容,然后替换该值或推送一个新值。

Array.reduce 的最后,我们将有一个包含代码、密钥和类型的对象。我们使用Array.map 对其进行变异以获得所需的输出。

// Assign a numeric value to every type of file you can get
// The purpose will be to be able to compare types altogether and
// choose which one to keep in case of conflict
function getTypeValue(type) {
  return ({
    PROCESS: 1,
    SUCCESS: 2,
    ERROR: 3,
  })[type];
}

const arr = [{
    Key: 'file/ERROR-FILE1-123.xlsx',
  },
  {
    Key: 'file/PROCESS-FILE1-123.xlsx',
  },
  {
    Key: 'file/PROCESS-FILE2-111.xlsx',
  },
  {
    Key: 'file/SUCCESS-FILE2-111.xlsx',
  },
  {
    Key: 'file/PROCESS-FILE3-121.xlsx',
  },
];

const ret = Object.values(arr.reduce((tmp, {
  Key
}) => {
  // use a regex to extract the interesting values 
  const [,
    type,
    code,
  ] = /(ERROR|PROCESS|SUCCESS)-FILE[0-9]{1}-([0-9]*).xlsx/.exec(Key);

  const typeValue = getTypeValue(type);

  if (tmp[code]) {
    // Check if the new entry should replace the one already stored
    if (tmp[code].typeValue < typeValue) {
      tmp[code] = {
        Key,
        typeValue,
      };
    }
  } else {
    tmp[code] = {
      Key,
      typeValue,
    };
  }

  return tmp;
}, {})).map(({
  Key,
}) => ({
  Key,
}));

console.log(ret);

【讨论】:

    【解决方案4】:
    
    // Sample Files Array
    var files = [
      {
        "Key": "file/ERROR-FILE1-123.xlsx",
      },
       {
        "Key": "file/PROCESS-FILE1-123.xlsx",
      },
      {
        "Key": "file/PROCESS-FILE2-111.xlsx",
      },
      {
        "Key": "file/SUCCESS-FILE2-111.xlsx",
      },
      {
        "Key": "file/PROCESS-FILE3-121.xlsx",
      },
    ]
    
    // This will contain final processed output
    var final_list = []
    
    // Creating priority for every status
    var priority = {
        "SUCCESS":1,
        "ERROR":2,
        "PROCESS":3
    }
    
    // Temporary object for storing status on the basis of filenames
    var temp = {}
    
    // Logic
    for(var i=0;i<files.length;i++){
     let file = files[i];
    // splitting filename "file/PROCESS-FILE1-123.xlsx" 
        let re = file.Key.split('/')[1].split('-');
        status = re[0]; // "PROCESS"
        filename = re[1]+"-"+re[2]; // "FILE1-123.xlsx"
        if(!(filename in temp)){
            temp[filename] = status;
        }else{
            if(priority[status] < priority[temp[filename]]){
            temp[filename] = status
            }
        }
    }
    
    // Making of final object
    for(key in temp){
        final_list.push({"Key":"files/"+temp[key]+"-"+key})
    }
    
    console.log(final_list);
    

    【讨论】:

      【解决方案5】:

      please check the stackbliz and the console of the code

      KeywordString = [
          {
            Key: "file/ERROR-FILE1-123.xlsx"
          },
          {
            Key: "file/PROCESS-FILE1-123.xlsx"
          },
          {
            Key: "file/PROCESS-FILE2-111.xlsx"
          },
          {
            Key: "file/SUCCESS-FILE2-111.xlsx"
          },
          {
            Key: "file/PROCESS-FILE3-121.xlsx"
          }
        ];
        newJSON = [];
        constructor() {
          let map = new Object();
      
          for (var index = 0; index < this.KeywordString.length; index++) {
      
            if (
              map[
                this.KeywordString[index].Key.substr(
                  this.KeywordString[index].Key.length - 15
                )
              ]
            ) {
      
            } else {
              map[
                this.KeywordString[index].Key.substr(
                  this.KeywordString[index].Key.length - 15
                )
              ] = true;
      
              this.newJSON.push(this.KeywordString[index]);
            }
          }
          console.log(this.newJSON);
        }
      }
      

      我把它做成了一个对象数组

      【讨论】:

        【解决方案6】:

        试试这个:https://runkit.com/embed/jmcxcv47el2f

        let arr = [
          {
            "Key": "file/ERROR-FILE1-123.xlsx",
          },
           {
            "Key": "file/PROCESS-FILE1-123.xlsx",
          },
          {
            "Key": "file/PROCESS-FILE2-111.xlsx",
          },
          {
            "Key": "file/SUCCESS-FILE2-111.xlsx",
          },
          {
            "Key": "file/PROCESS-FILE3-121.xlsx",
          },
        ];
        
        const filterBy = (keep, remove1, remove2) => {
            let values = arr.map(item => item.Key);
            let keeps = values.filter(item => item.includes(keep));
            let names = keeps.map(item => item.replace(`file/${keep}-FILE`,""));    
            names.forEach(name => {       
               arr = arr.filter(item => item.Key !==`file/${remove1}-FILE${name}`);
               if(remove2)
                  arr = arr.filter(item => item.Key !==`file/${remove2}-FILE${name}`);
            });    
        }
        
        filterBy("ERROR", "SUCCESS", "PROCESS");
        filterBy("SUCCESS", "PROCESS");
        //arr <<-- This is output;
        

        【讨论】:

        • 现在我正在处理动态文件所以获取这种 json 数据 [{ERROR-FILE1-2020.xlsx},{PROCESS-FILE1-2020.xlsx},{errorbyte.xlsx}, {SUCCESS-FILE2-2020.xlsx},{PROCESS-FILE2-2020.xlsx},{PROCESS-FILE3-2020.xlsx}]
        • 没关系,适应这个方案就行了。
        猜你喜欢
        • 1970-01-01
        • 2017-01-28
        • 1970-01-01
        • 2021-11-29
        • 1970-01-01
        • 2020-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多