批量替换json中的字段名

const replaceSome = (repalceNames = []) => (originObj = {}) => repalceNames.reduce(((total, { o, n }) => Object.assign(total, { [n]: originObj[o] })), {});
// const obj = {name:'哈喽',age:'12'};
// const repalceNames = [{o:'name',n:'newName'},{o:'age',n:'newAge'},]
// replaceNameBatch(obj,repalceNames); => {newName:'哈喽',newAge:'12'};
const obj = { name: '哈喽', age: '12' };
const names = [{ o: 'name', n: 'newName' }, { o: 'age', n: 'newAge' }];

const replaceSome = (repalceNames = []) => (originObj = {}) => repalceNames.reduce(((total, { o, n }) => Object.assign(total, { [n]: originObj[o] })), {});

const replaceNameBatch = replaceSome(names);

const res = replaceNameBatch(obj, names);
console.log(res); // { newName: '哈喽', newAge: '12' }

 

你可能感兴趣的:(批量替换json中的字段名)