0

I want to convert the fileID that is in the current array from string to number, e.g: fileID: "1" to fileID: 1.

How to target the specific item (fileID) so that I can convert it to a number and map the current array into a new array?

Current array:

[
    {
      fileID: "1",
      fileName: "Cardio Care Awareness Month",
      createdByID: "100101"
    },
    {
      fileID: "2",
      fileName: "MEMO COMPULSORY TO",
      createdByID: "100101"
    },
    {
      fileID: "3",
      fileName: "MEMO 2021 Covid19 Vaccination Leave",
      createdByID: "200201"
    },
    {
      fileID: "4",
      fileName: "Human Cell",
      createdByID: "200201"
    }
]

New converted array:

[
    {
      fileID: 1,
      fileName: "Cardio Care Awareness Month",
      createdByID: "100101"
    },
    {
      fileID: 2,
      fileName: "MEMO COMPULSORY TO",
      createdByID: "100101"
    },
    {
      fileID: 3,
      fileName: "MEMO 2021 Covid19 Vaccination Leave",
      createdByID: "200201"
    },
    {
      fileID: 4,
      fileName: "Human Cell",
      createdByID: "200201"
    }
]

enter image description here

1
  • 1
    How about array.map(i => {...i, fileID: parseInt(i.fileID))}? Commented Oct 21, 2021 at 5:48

2 Answers 2

1

Here is a function that should convert the array into the format you want.

const convertArray = array => array.map(({fileID, ...item}) => ({fileID: Number(fileID), ...item}))
Sign up to request clarification or add additional context in comments.

Comments

1

You can create a custom function and re-use it in your application.

Example :

const parseData = (data, key) => {
    return data.map(item => {
        return {
         ...item,
         [key] : Number(item[key])
        }
    })
}

parseData(data, 'fileID')

0: {fileID: 1, fileName: 'Cardio Care Awareness Month', createdByID: '100101'}
1: {fileID: 2, fileName: 'MEMO COMPULSORY TO', createdByID: '100101'}
2: {fileID: 3, fileName: 'MEMO 2021 Covid19 Vaccination Leave', createdByID: '200201'}
3: {fileID: 4, fileName: 'Human Cell', createdByID: '200201'}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.