skip to Main Content

i have an array below

const sampleResponse = [
    {
      benefitTypeCode: 'HE',
      benefitTypeValue: 'HEALTH',
    },
    {
      benefitTypeCode: 'DE',
      benefitTypeValue: 'DEATH',
    },
  ];

how to manipulate array string into our desire string

my goals

const sampleResponse = [
    {
      benefitTypeCode: 'HE',
      benefitTypeValue: 'live',
    },
    {
      benefitTypeCode: 'DE',
      benefitTypeValue: 'passed away',
    },
  ];

need advise.. sorry im newbie , thanks a lot btw.

3

Answers


  1. simply make object for it and use it’s index

    like this :

    const dictionary = {
      HEALTH: 'live',
      DEATH: 'passed away',
    };
    
    const sampleResponse = [
      {
        benefitTypeCode: 'HE',
        benefitTypeValue: dictionary['HEALTH'],
      },
      {
        benefitTypeCode: 'DE',
        benefitTypeValue: dictionary['DEATH'],
      },
    ];
    
    Login or Signup to reply.
  2. Try this approach:

    Create a map with new values

    const newBenefitTypes = {
      HEALTH: 'live',
      DEATH:  'passed away',
    }
    

    And convert old array

    const newResponse = sampleResponse.map(item => ({
      ...item,
      benefitTypeValue: newBenefitTypes[item.benefitTypeValue],
    }))
    
    Login or Signup to reply.
  3. It’s an object. So, you can iterate through it and change the value of your desired key you want to modify. Hope, the below code will be helpful.

    sampleResponse.forEach((element) => {
      if (element.benefitTypeCode === 'HE') {
        element.benefitTypeValue = 'live'
      } else {
        if (element.benefitTypeCode === 'DE') {
          element.benefitTypeValue = 'passed away'
        }
      }
    })
    

    console.log(sampleResponse)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search