按字段设置对象格式


const data = {
language: 'en',
type: 'trx',
country: 'Croatia',
Method: 'trx_pay',
Email: 'email',
Phone: '123',
City: 'Zagreb'
}

我需要将上述对象格式化为这样的格式:

const data = {
language: 'en',
type: 'trx',
country: 'Croatia',
userData: {
Method: 'trx_pay',
Email: 'email',
Phone: '123',
City: 'Zagreb'
}
}

PascalCase中的所有字段都应该放在一个嵌套对象中。此外,我确切地知道camelCase中的字段(语言、类型和国家(。

以下是我迄今为止使用Lodash:所做的尝试

const staticKeys = ['language', 'type', 'country']; // These keys can't changes
const staticData = pick(data, staticKeys);
const userData = omit(data, staticKeys);
const res = { ...staticData, userData };

有没有一种更优雅的方法可以在没有洛达什的情况下做到这一点?

如果不想使用lodash,可以使用析构函数赋值。由于您知道静态键,因此可以对它们进行解构(而不是将它们放入数组中(,并使用rest语法(...(来获得所有其他剩余属性:

const data = { language: 'en', type: 'trx', country: 'Croatia', Method: 'trx_pay', Email: 'email', Phone: '123', City: 'Zagreb' };
const {language, type, country, ...userData} = data;
const res = {language, type, country, userData};
console.log(res);

使用Object.entries((的香草js循环

const staticKeys = ['language', 'type', 'country'];
const data = {
language: 'en',
type: 'trx',
country: 'Croatia',
Method: 'trx_pay',
Email: 'email',
Phone: '123',
City: 'Zagreb'
}
const res = {userData:{}}
Object.entries(data).forEach(([k,v])=> (staticKeys.includes(k) ? res : res.userData)[k] = v)
console.log(res)

最新更新