js数据格式转换?

{
    "withDiffDeptPersonId": "00004833,00009278",
    "withDiffDeptCode": "30120832,30120832",
    "withDiffDeptPersonName": "米久华,罗贻泽",
    "withSameDeptPersonId": "00012765,00029927",
    "withSameDeptCode": "30120769,30000769",
    "withSameDeptPersonName": "王璐,潘燕玲"
}

上边格式如何转换为以下格式

[
    {
        "personId": "00004833",
        "deptCode": "30120832",
        "personName": "米久华",
        "isDiff": true
    },
    {
        "personId": "00009278",
        "deptCode": "30120832",
        "personName": "罗贻泽",
        "isDiff": true
    },
    {
        "personId": "00012765",
        "deptCode": "3012769",
        "personName": "王璐",
        "isDiff": false
    },
    {
        "personId": "00029927",
        "deptCode": "30000769",
        "personName": "潘燕玲",
        "isDiff": false
    }
]
阅读 3.4k
6 个回答

更新:这里看到多次getValues(key, '')的调用,强迫症促使我思考能不能优化掉,于是有了下面这段代码,但是更不容易看懂了

function transform(data) {
    const getValues = (mid, suffix) => data[`with${mid}Dept${suffix}`].split(',');
    const splitData = key => (values => values('PersonId').map((id, i) => ({
        personId: id,
        deptCode: values('Code')[i],
        personName: values('PersonName')[i],
        isDiff: key === 'Diff',
    })))(suffix => getValues(key, suffix));

    return splitData('Diff').concat(splitData('Same'))
}

transform({
    "withDiffDeptPersonId": "00004833,00009278",
    "withDiffDeptCode": "30120832,30120832",
    "withDiffDeptPersonName": "米久华,罗贻泽",
    "withSameDeptPersonId": "00012765,00029927",
    "withSameDeptCode": "30120769,30000769",
    "withSameDeptPersonName": "王璐,潘燕玲"
})

通过一个IIFE将这个传入的key函数柯里化,调用values('...')实际上相当于getValues(key, '...')


function transform(data) {
    const getValues = (mid, suffix) => data[`with${mid}Dept${suffix}`].split(',');
    const splitData = key => getValues(key,'PersonId').map((id, i) => ({
        personId: id,
        deptCode: getValues(key, 'Code')[i],
        personName: getValues(key, 'PersonName')[i],
        isDiff: key === 'Diff',
    }));

    return splitData('Diff').concat(splitData('Same'))
}

transform({
    "withDiffDeptPersonId": "00004833,00009278",
    "withDiffDeptCode": "30120832,30120832",
    "withDiffDeptPersonName": "米久华,罗贻泽",
    "withSameDeptPersonId": "00012765,00029927",
    "withSameDeptCode": "30120769,30000769",
    "withSameDeptPersonName": "王璐,潘燕玲"
})
Object.entries(data).reduce((obj, [key, val]) => {

    // 判断是否 Diff
    let isDiff = /Diff/.test(key);

    // 截取键名后两个单词,并转换首字母为小写
    key = key.match(/(?:.[a-z]+){2}$/)[0].replace(/^./, c => c.toLowerCase());

    // 用 ',' 切割值,并以 key 为键名,赋给 isDiff 数组里 idx 处(不存在自动新建)
    val.split(',').forEach((val, idx) => (obj[+isDiff][idx] ??= {isDiff})[key] = val);

    // 返回缓存值,继续迭代下一键值对
    return obj;

} , [[], []]).flat()
const data = {
    "withDiffDeptPersonId": "00004833,00009278",
    "withDiffDeptCode": "30120832,30120832",
    "withDiffDeptPersonName": "米久华,罗贻泽",
    "withSameDeptPersonId": "00012765,00029927",
    "withSameDeptCode": "30120769,30000769",
    "withSameDeptPersonName": "王璐,潘燕玲"
};

const personIds = data.withDiffDeptPersonId.split(',');
const deptCodes = data.withDiffDeptCode.split(',');
const personNames = data.withDiffDeptPersonName.split(',');

const result = personIds.map((personId, index) => ({
    personId,
    deptCode: deptCodes[index],
    personName: personNames[index],
    isDiff: true
}));

const samePersonIds = data.withSameDeptPersonId.split(',');
const sameDeptCodes = data.withSameDeptCode.split(',');
const samePersonNames = data.withSameDeptPersonName.split(',');

samePersonIds.forEach((personId, index) => {
    result.push({
        personId,
        deptCode: sameDeptCodes[index],
        personName: samePersonNames[index],
        isDiff: false
    });
});

console.log(result);

企业微信截图_16880273415792.png

const getFormatData = (oldData) => {
    const rObj = {
        withDiff: [],
        withSame: [],
    };
    for (let item in oldData) {
        let arr = oldData[item].split(',');
        let key = Object.keys(rObj).find((k) => item.includes(k));
        if (key !== undefined) {
            let rKey = item.replace(key, '');
            arr.forEach((obj, index) => {
                if (!rObj[key][index]) rObj[key][index] = {
          isDiff:key==='withDiff'
        };
                rObj[key][index][rKey] = obj;
            });
        }
    }
  return [...rObj.withDiff,...rObj.withSame]
};
const a1 = {
  withDiffDeptPersonId: '00004833,00009278',
  withDiffDeptCode: '30120832,30120832',
  withDiffDeptPersonName: '米久华,罗贻泽',
  withSameDeptPersonId: '00012765,00029927',
  withSameDeptCode: '30120769,30000769',
  withSameDeptPersonName: '王璐,潘燕玲',
};
console.log(getFormatData(a1));
const data = {
    "withDiffDeptPersonId": "00004833,00009278",
    "withDiffDeptCode": "30120832,30120832",
    "withDiffDeptPersonName": "米久华,罗贻泽",
    "withSameDeptPersonId": "00012765,00029927",
    "withSameDeptCode": "30120769,30000769",
    "withSameDeptPersonName": "王璐,潘燕玲"
};

const keyMap = {
    "withDiffDeptPersonId": "personId",
    "withDiffDeptCode": "deptCode",
    "withDiffDeptPersonName": "personName",
    "withSameDeptPersonId": "personId",
    "withSameDeptCode": "deptCode",
    "withSameDeptPersonName": "personName"
};

const obj = Object.entries(data)
    .map(([key, value]) => [keyMap[key], value.split(",")])
    .reduce((result, [key, values]) => {
        (result[key] ??= []).push(...values);
        return result;
    }, {});

const result = Object.entries(obj)
    .flatMap(([key, list]) => list.map((v, i) => [key, v, i]))
    .reduce((r, entry) => {
        (r[entry[2]] ??= {})[entry[0]] = entry[1];
        return r;
    }, []);

console.log(result);
const input = {
  "withDiffDeptPersonId": "00004833,00009278",
  "withDiffDeptCode": "30120832,30120832",
  "withDiffDeptPersonName": "米久华,罗贻泽",
  "withSameDeptPersonId": "00012765,00029927",
  "withSameDeptCode": "30120769,30000769",
  "withSameDeptPersonName": "王璐,潘燕玲"
};

const diffIds = input.withDiffDeptPersonId.split(',');
const diffCodes = input.withDiffDeptCode.split(',');
const diffNames = input.withDiffDeptPersonName.split(',');
const sameIds = input.withSameDeptPersonId.split(',');
const sameCodes = input.withSameDeptCode.split(',');
const sameNames = input.withSameDeptPersonName.split(',');

const result = [];

for (let i = 0; i < diffIds.length; i++) {
  result.push({
    personId: diffIds[i],
    deptCode: diffCodes[i],
    personName: diffNames[i],
    isDiff: true
  });
}

for (let i = 0; i < sameIds.length; i++) {
  result.push({
    personId: sameIds[i],
    deptCode: sameCodes[i],
    personName: sameNames[i],
    isDiff: false
  });
}

console.log(result);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏