Home > OS >  How to slice the name in the array of objects discluding the names without (T1) or (T2)
How to slice the name in the array of objects discluding the names without (T1) or (T2)

Time:06-08

I'm having Problem with slicing an array of objects

const agent = [
  {
    "agent-name": "Jm Fajardo",
    "gender": "Male"
  },
  {
    "agent-name": "Lem Cruz (T1)",
    "gender": "Male"
  },
  {
    "agent-name": "Levi Fajarda (T2)",
    "gender": "Male"
  },
  {
    "agent-name": "Ian Pacido",
    "gender": "Male"
  }
];


$.each(agent, function (key, value) {
  var sliced = value["agent-name"].slice(0, -5);
  console.log("agent :", sliced);
});

This is the output I get:

agent : Jm Fa
agent : Lem Cruz
agent : Levi Fajarda
agent : Ian P

This is the output i tried to get

agent : Jm Fajardo
agent : Lem Cruz
agent : Levi Fajarda
agent : Ian Pacido

CodePudding user response:

You can use a regular expression to only match patterns like (T1) or (T2).

const agent = [{
    "agent-name": "Jm Fajardo",
    "gender": "Male"
  },
  {
    "agent-name": "Lem Cruz (T1)",
    "gender": "Male"
  },
  {
    "agent-name": "Levi Fajarda (T2)",
    "gender": "Male"
  },
  {
    "agent-name": "Ian Pacido",
    "gender": "Male"
  }
];


$.each(agent, function(key, value) {
  var sliced = value["agent-name"].replace(/\s*\(T\d\)$/, '');
  console.log("agent :", sliced);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Explanation:

  • \s*: all spaces before the pattern
  • \(T\d\): match all (Tx) where x is a digit
  • $: at the end of the string

$ can be omitted to match (Tx) anywhere in the string.

CodePudding user response:

If you would like to avoid regular expressions you could try testing for the presence of T1 or T2 and then only applying your slice function if one of them is present.

I think using regexp would probably be a more generally applicable approach.

const agent = [{
    "agent-name": "Jm Fajardo",
    "gender": "Male"
  },
  {
    "agent-name": "Lem Cruz (T1)",
    "gender": "Male"
  },
  {
    "agent-name": "Levi Fajarda (T2)",
    "gender": "Male"
  },
  {
    "agent-name": "Ian Pacido",
    "gender": "Male"
  }
];


$.each(agent, function(key, value) {
  if(value["agent-name"].includes(['T1']) || value["agent-name"].includes(['T2'])){
    var sliced = value["agent-name"].slice(0, -5);
  } else {
    var sliced = value["agent-name"];
  }
  
  console.log("agent :", sliced);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  • Related