将JSON对象与相同数量的键值对组合,附加主键值

时间:2018-02-12 09:46:40

标签: javascript arrays json

我在几年前编写的一个解析器程序中有以下JSON对象。

{"Date":"19/02/16","Narration":"NEFT DR-BARB0PIMPAL-Govt. NE","Chq":{"/Ref":{"No":{"":"N050160130709970"}}},"Value Dt":"19/02/16","Withdrawal Amt":{"":"8,000.00"},"Deposit Amt":{"":""},"Closing Balance":"24,114.95"}

{"Date":"","Narration":"TBANK, MUM-N050160130709970","Chq":{"/Ref":{"No":{"":""}}},"Value Dt":"","Withdrawal Amt":{"":""},"Deposit Amt":{"":""},"Closing Balance":""}

基本上,上述条目应该是单一记录。但是,由于换行,解析器将它们视为新记录。

我尝试通过将对象转换为数组来映射对象。但是,地图会产生以下JSON对象。

{"Date":"19/02/16"}{"Date":""},{"Narration":"NEFT DR-BARB0PIMPAL-Govt. NE"}{"Narration":"TBANK, MUM-N050160130709970"},{"Chq":{"/Ref":{"No":{"":"N050160130709970"}}}}{"Chq":{"/Ref":{"No":{"":""}}}},{"Value Dt":"19/02/16"}{"Value Dt":""},{"Withdrawal Amt":{"":"8,000.00"}}{"Withdrawal Amt":{"":""}},{"Deposit Amt":{"":""}}{"Deposit Amt":{"":""}},{"Closing Balance":"24,114.95"}{"Closing Balance":""}

我需要的是一个合并/组合数组OR对象,主键保持不变,值连接/追加到第一个元素(此后要丢弃的第二个对象。)

例如。

{"Date":"19/02/16","Narration":"NEFT DR-BARB0PIMPAL-Govt.NETBANK","Chq":{"/Ref":{"No":{"":"N050160130709970MUM-N050160130709970"}}},"Value Dt":"19/02/16","Withdrawal Amt":{"":"8,000.00"},"Deposit Amt":{"":""},"Closing Balance":"24,114.95"}

你们可以建议我是否可以直接合并/组合源JSON对象或将数组与上述效果合并?

2 个答案:

答案 0 :(得分:1)

显然你需要知道这些对象的顺序,所以我假设你有一个数组,所有数组都从JSON解析为JavaScript对象。

其次,我假设一个记录是前一个记录的延续,可以通过空余额字段识别(例如 - 根据需要进行调整)。

以下是执行合并的代码:

function mergeSplitObjects(arr) {
    return arr.filter( (curr, i) => {
        // Does this look like a split-off object that should be merged with previous?
        if (curr["Closing Balance"] !== "") { // Adapt condition as needed
            return true; // No, it is a real record
        }
        arr[i-1]["Narration"] += curr["Narration"]; // Merge, and filter curr out
    });
}

// Sample data with 3 records. First two should be merged
let arr = [
    {"Date":"19/02/16","Narration":"NEFT DR-BARB0PIMPAL-Govt. NE","Chq":{"/Ref":{"No":{"":"N050160130709970"}}},"Value Dt":"19/02/16","Withdrawal Amt":{"":"8,000.00"},"Deposit Amt":{"":""},"Closing Balance":"24,114.95"},
    {"Date":"","Narration":"TBANK, MUM-N050160130709970","Chq":{"/Ref":{"No":{"":""}}},"Value Dt":"","Withdrawal Amt":{"":""},"Deposit Amt":{"":""},"Closing Balance":""},
    {"Date":"20/02/16","Narration":"ATM NYC 13","Chq":{"/Ref":{"No":{"":"N050160130709971"}}},"Value Dt":"20/02/16","Withdrawal Amt":{"":"1,000.00"},"Deposit Amt":{"":""},"Closing Balance":"23,114.95"},
];
arr = mergeSplitObjects(arr);

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

答案 1 :(得分:1)

我会使用类似于Object.assign的函数。

就像Trincot一样,我假设Closing Balance表示要合并的记录。

var splitRegExp = /[a-z],\s*[a-z]/gi;
function deepMergingAssign(obj /*, sourceObjects*/){
    'use strict';
    if (obj == null) throw new TypeError('Cannot convert undefined or null to object');
    var final = Object(obj);
    [].slice.call(arguments, 1).forEach(function(arg){
        if(arg != null) {
            for(var prop in arg) {
                if (typeof arg[prop] === 'object'&&typeof final[prop] === 'object') {
                    // recursively call this function
                    arg[prop] = deepMergingAssign(final[prop],arg[prop]);
                    delete arg[prop]
                }
                else if(Object.prototype.hasOwnProperty.call(arg,prop)) {
                    // append the new values to the existing value.
                    var currentValue = final[prop].split(splitRegExp);
                    var incomingValue = arg[prop].split(splitRegExp);
                    incomingValue.forEach( function(val){
                        if (val! == '' && currentValue.indexOf(val) === -1) currentValue.push(val);
                    });
                    final[prop] = currentValue.join(', ');
                }
            }
        }
    });
    return final;
}

function mergeRecords(records){
    var toMerge = [];
    var mergedData = []
    for (var i=0; i<records.length; i++){
        // Change this condition as needed
        if (records[i]['Closing Balance'] !== '' && toMerge.length>0){
            // Create a merged record and reset the toMerge variable
            mergedData.push(deepMergingAssign.apply(null, toMerge));
            toMerge = [records[i]];
        }
        else {
            // This record should be merged with the previous.
            toMerge.push(records[i]);
        }
    }
    // Merge the last records stored in the array
    mergedData.push(deepMergingAssign.apply(null, toMerge));

    return mergedData;
}

var allRecords = [
    {"Date":"19/02/16","Narration":"NEFT DR-BARB0PIMPAL-Govt. NE","Chq":{"/Ref":{"No":{"":"N050160130709970"}}},"Value Dt":"19/02/16","Withdrawal Amt":{"":"8,000.00"},"Deposit Amt":{"":""},"Closing Balance":"24,114.95"},
    {"Date":"","Narration":"TBANK, MUM-N050160130709970","Chq":{"/Ref":{"No":{"":""}}},"Value Dt":"","Withdrawal Amt":{"":""},"Deposit Amt":{"":""},"Closing Balance":""},
    {"Date":"21/02/16","Narration":"TBANK","Chq":{"/Ref":{"No":{"":"N050160130709971"}}},"Value Dt":"21/02/16","Withdrawal Amt":{"":""},"Deposit Amt":{"":"2,000.00"},"Closing Balance":"26,114.95"},
    {"Date":"22/02/16","Narration":"TBANK","Chq":{"/Ref":{"No":{"":"N050160130709972"}}},"Value Dt":"22/02/16","Withdrawal Amt":{"":"5,750.00"},"Deposit Amt":{"":"1,000.00"},"Closing Balance":"21,364.95"},
    {"Date":"","Narration":"TBANK, MUM-N050160130709972","Chq":{"/Ref":{"No":{"":""}}},"Value Dt":"","Withdrawal Amt":{"":""},"Deposit Amt":{"":""},"Closing Balance":""}
]

var merged = mergeRecords(allRecords);
/* [
    record 1+2,
    record 3,
    record 4+5
   ] */