lecham
lecham

Reputation: 2464

Format an object by fields

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

I need format the above object into such format:

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

All the fields in PascalCase should be put into a nested object. Also, I know exactly the fields in camelCase (language, type and country).

Here's what I've tried so far using 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 };

Is there a more elegant way to do it without Lodash?

Upvotes: 1

Views: 166

Answers (2)

charlietfl
charlietfl

Reputation: 171679

Using a vanilla js loop of the Object.entries()

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)

Upvotes: 0

Nick Parsons
Nick Parsons

Reputation: 50664

If you don't want to use lodash, you can make use of destructuring assignment. Since you know the static keys, you can destructure them (rather than put them into an array), and use the rest syntax (...) to obtain all the other remaining properties:

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

Upvotes: 2

Related Questions