skip to Main Content

Hi I am getting some data from api and one particular value need to be in proper way. Can you please provide some kind of solution for this ?

const data = [ 
{ state: 'Test-1.5', response: "ABC" },
{ state: 'Test-2.5', response: "XYZ" },
{ state: 'Test', response: "GHD" },
];

Below should be expected data after format, need to remove the number from state which start from (-) if it is exist

const expectedData = [ 
{ state: 'Test', response: "ABC" },
{ state: 'Test', response: "XYZ" },
{ state: 'Test', response: "GHD" },
];

2

Answers


  1. You can try mapping the array, splitting the text in "-" and get what comes before it, like this:

    const data = [ 
    { state: 'Test-1.5', response: "ABC" },
    { state: 'Test-2.5', response: "XYZ" },
    { state: 'Test', response: "GHD" },
    ];
    
    const formatted = data.map(data => ({...data, state: data.state.split("-")[0]}))
    
    console.log(formatted)
    Login or Signup to reply.
  2. const data = [ 
    { state: 'Test-1.5', response: "ABC" },
    { state: 'Test-2.5', response: "XYZ" },
    { state: 'Test', response: "GHD" },
    ];
    
    // pure 
    const result = data.map(({state, ...props}) => ({state: state.replace(/-[d.]+$/, ''), ...props}));
    console.log(JSON.stringify(result));
    
    // mutable
    data.forEach(item => item.state = item.state.replace(/-[d.]+$/, ''));
    console.log(JSON.stringify(data));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search