Home > OS >  Spliting json data
Spliting json data

Time:12-14

The following example to split the json data

  ``` var data = [ { BankName: 'SBI', IFSC: 'SBIN0002688' }, 
  { BankName: 'ICICI', IFSC: 'ICIC0003931',MICR : '500229094'},
  { BankName: 'RBI', IFSC: 'RBIS0GOTGEP' }, 
  { BankName: 'CITI', IFSC: 'CITI0000047',MICR : '500229034'} ]```  

I need the results here

 
  let result = [ {BankName: 'SBI','Codes':['SBIN0002688']},
  {BankName: 'ICICI','Codes':['ICIC0003931','500229094']},
  {BankName: 'RBI','Codes':['RBIS0GOTGEP']},
  {BankName: 'CITI','Codes':['CITI0000047','500229034']} ] 

CodePudding user response:

You can map the data and then for each item, isolate the BankName from the rest of the properties (assuming that the rest of the properties are "Codes").

var data = [ { BankName: 'SBI', IFSC: 'SBIN0002688' }, 
  { BankName: 'ICICI', IFSC: 'ICIC0003931',MICR : '500229094'},
  { BankName: 'RBI', IFSC: 'RBIS0GOTGEP' }, 
  { BankName: 'CITI', IFSC: 'CITI0000047',MICR : '500229034'} ]

const result = data.map(({ BankName, ...codes }) => ({
  BankName,
  Codes: Object.values(codes),
}));

console.log(result);

CodePudding user response:

var data = [
  { BankName: 'SBI', IFSC: 'SBIN0002688' },
  { BankName: 'ICICI', IFSC: 'ICIC0003931', MICR: '500229094' },
  { BankName: 'RBI', IFSC: 'RBIS0GOTGEP' },
  { BankName: 'CITI', IFSC: 'CITI0000047', MICR: '500229034' },
];

const result = data.map((val) => {
  return {
    BankName: val.BankName,
    Codes: val.MICR ? [val.IFSC, val.MICR] : [val.IFSC],
  };
});

The above snippet should work

  • Related