Search code examples
typescriptlodash

how to remove first two characters in object array using lodash


This question might be simple! I am working in an angular project. Consider my array format is like below.

 "dataItem": [
    {
        "id": "1",
        "caption": "01   Data One"
    },
    {
        "id": "2",
        "caption": "02   Data Two"
    },
    {
        "id": "3",
        "caption": "03   Data Three"
    }   
]

In the caption property, I want to strip off first two characters (i.e. 01, 02, 03). So, the caption would be something similar like below

"dataItem": [
    {
        "id": "1",
        "caption": "Data One"
    },
    {
        "id": "2",
        "caption": "Data Two"
    },
    {
        "id": "3",
        "caption": "Data Three"
    }   
]

Is there a way to use lodash to write one or two lines of code to achieve this? I tried other resources, but could not get vertical slices in a simple way!


Solution

  • Something like this would work,

    const lodash = require('lodash')
    
    const data = {
      "dataItem": [
        {
            "id": "1",
            "caption": "01   Data One"
        },
        {
            "id": "2",
            "caption": "02   Data Two"
        },
        {
            "id": "3",
            "caption": "03   Data Three"
        }   
    ]
    }
    
    const result = lodash.map(data.dataItem, item => {
      // substring from 5 because number and spaces seem to end at fifth position
      return { ...item, caption: item.caption.substring(5) }
    })