Home > Back-end >  How to manipulate object of array with properties to different names and return the result in a sing
How to manipulate object of array with properties to different names and return the result in a sing

Time:10-06

I have a request data - array of object like below:

const requestData = [
  {
    name: 'Test1',
    address: 'FL',
  },
  {
    name: 'Test2',
    address: 'AL',
  },
  {
    name: 'Test3',
    address: 'AK',
  },
]; 

I want to manipulate the object properties based on the index (that mean if index 0 change name property to USER_NAME, if index 1 means change to EMP_NAME) and convert it into final object as below:

const finalResult = {
  USER_NAME: 'Test1',
  USER_ADDRESS: 'FL',
  EMP_NAME: 'Test2',
  EMP_ADDRESS: 'AL',
  CUST_NAME: 'Test3',
  CUST_ADDRESS: 'AK',
};

CodePudding user response:

Using reduce() and an extra map array can do it

let data = [{
    name: 'Test1',
    address: 'FL',
  },
  {
    name: 'Test2',
    address: 'AL',
  },
  {
    name: 'Test3',
    address: 'AK',
  },
]

let mdata =['USER_','EMP_','CUST_']

let result = data.reduce((a,v,i) =>{
  let key = mdata[i]
  a[key 'NAME'] = v.name
  a[key 'ADDRESS'] = v.address
  return a
},{})

console.log(result)

CodePudding user response:

You could destructure and construct your final result:

const [ user, emp, cust ] = requestData;

const finalResult = {
    USER_NAME: user.name,
    USER_ADDRESS: user.address,
    EMP_NAME: emp.name,
    EMP_ADDRESS: emp.address,
    CUST_NAME: cust.name,
    CUST_ADDRESS: cust.address
};

Alternatively, you could reduce, but the code winds up being a bit more complicated than is necessary for this particular example:

const keys = [ "USER", "EMP", "CUST" ];

const finalResult = requestData.reduce(( out, { name, address }, index ) => {
    out[ `${ keys[ index ] }_NAME` ] = name;
    out[ `${ keys[ index ] }_ADDRESS` ] = address;
    return out;
}, {});
  • Related