SOURCE

let str = '公司名称:杭州凡闻科技有限公司,公司地址:杭州西湖区文一西路 1 号海创园 2 幢 3 楼,开票单位:杭州中力搬运设备有限公司,注册地址:杭州市下城区永华街 121 号 2 幢 307、308 室,开户行账号:工行建国北路支行,税号:91330103722781873R,结算账户:1202022209006744846,电话:0571-28035601'

let template = {
    buyer: '',
    deliveryAddress: '',
    invoicingInformation: {
        company: '',
        address: '',
        bankAccount: '',
        settlementAccount: '',
        phoneNumber: '',
        taxId: ''
    }
}


const matchup = {
    buyer: '公司名称',
    deliveryAddress: '公司地址',
    company: '开票单位',
    address: '注册地址',
    bankAccount: '开户行账号',
    taxId: '税号',
    settlementAccount: '结算账户',
    phoneNumber: '电话',
    model: '产品名称',
    piece: '数量',
    price: '单价',
    amount: '金额',
    spec_LoadCapacity: '额定载重',
    spec_LiftingHeight: '举升高度',
    spec_ForkDimensions: '货叉尺寸',
    spec_Battery: '电池',
    spec_Charger: '充电器',
    spec_Color: '颜色'
};

function parseJson(str, template) {
    console.log(str, template)
    let list = str.split(',')
    console.log(list)
    list.forEach(item => {
        let [k, v] = item.split(':')
        console.log(k, v)
        Object.entries(matchup).forEach(([key, value]) => {
            if (k === value) {
                setValue(key, v, template);
            }
        })
    })
    console.log('解析结果', template)
}

function setValue(key, value, template) {
    // 当前层直接匹配成功
    if (Object.prototype.hasOwnProperty.call(template, key)) {
        template[key] = value;
        return true;
    }
    // 递归检查子对象
    for (let k in template) {
        if (template[k] && typeof template[k] === 'object') {
            const updated = setValue(key, value, template[k]);
            if (updated) return true;
        }
    }
    return false; // 没找到匹配键
}


parseJson(str, template);
console 命令行工具 X clear

                    
>
console