Viswa
Viswa

Reputation: 821

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!

Upvotes: 0

Views: 179

Answers (2)

Sandeep
Sandeep

Reputation: 21144

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) }
})

Upvotes: 1

SeekerDK
SeekerDK

Reputation: 1

You can use vanilla JS to do that.

for (item of dataItem) {
  item.caption = item.caption.substring(2).replace(/(^\s+|\s+$)/g, "");
}
console.log(dataItem);

If you really want to use lodash, it would look something like this (not tested)

_.forEach(dataItem, function(item) {
  item.caption = item.caption.substring(2).replace(/(^\s+|\s+$)/g, "");
});

Upvotes: 0

Related Questions