Home > OS >  JS - How to delete a substring that may or may not exist?
JS - How to delete a substring that may or may not exist?

Time:07-05

I want to store each of the fields in "text" as its own variable (for example, I want name = Biggie Wiggles, age = 49, etc) and also delete the hobbies section. In the actual data I am using, the "hobbies" field does not always occur, depending on whether it is filled out or not. What is the best way to accomplish this? Thanks in advance

"items": [
        {
            "id": "123",
            "text": "Name: Biggie Wiggles Age: 49 Hobbies: Playing golf, catching flies Birthday: 1/1/01",
            "created": "2022-07-04T15:16:41.984Z"
        }
]

CodePudding user response:

The problem is that the server isn't giving you great data to work with. You'll have to parse the values from the "text" property into fields you create yourself on the object.

Here's a super simple example of an implementation you can try. It iterates over your array with the .map method, parsing the values of the "text" property into new fields in a new object. Note that this implementation only works if the order of fields in the "text" property doesn't change, but this should be enough to point you in the right direction.

var items = [
  {
    "id"      : "123",
    "text"    : "Name: Biggie Wiggles Age: 49 Hobbies: Playing golf, catching flies Birthday: 1/1/01",
    "created" : "2022-07-04T15:16:41.984Z"
  }
].map(item => {
  // we're making an BIG assumption that the order
  // of fields in teh "text" property will always be the same
  var ageIndex   = x.text.indexOf("Age:");
  var hobbyIndex = x.text.indexOf("Hobbies:");

  return {
   id      : x.id,
   created : x.created,
   name    : x.text.substr(0,ageIndex).replace("Name:","").trim(),
   age     : x.text.substring(ageIndex,hobbyIndex).replace("Age:","").trim(),
   hobbies : x.text.substr(hobbyIndex).replace("Hobbies:","").trim()
  }
});

console.log(items);

CodePudding user response:


let obj ={id: "123", text: "Field 1: xyz Field 2: abc Field 3: lol"}; 
let newObj = obj.text.replace("Field 2: abc", '');  
obj[ 'text'] = newObj 
console.log(obj);

  • Related