0

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!

2 Answers 2

1

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) }
})
Sign up to request clarification or add additional context in comments.

1 Comment

This works like charm! Thanks @Sandeep. Instead of substring(5), I used substring(2).trim(). Thank you.
0

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, "");
});

1 Comment

Thanks @SeekerDK. Unfortunately, I am getting the error when I tried to assign caption property: "ERROR TypeError: Cannot assign to read only property 'caption' of object '[object Object]'" using vanilla JS. checking on that. appreciate your swift response. Its useful.

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.