javascript - 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
    }
]

 

第 1 个答案:

更新:这里看到多次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": "王璐,潘燕玲"
})

 

第 2 个答案:

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()

 

第 3 个答案:

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


 

第 4 个答案:

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));

 

第 5 个答案:

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);

 

第 6 个答案:

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);

https://www.firstui.cn/https://doc.firstui.cn/有用过这个组件库的吗?感觉怎么样?还有这组件是收费的??