0

i wanted represent first two letters of phone number,i want to get phone numbers first two characters. what i have tried is below Get first two of attribute and find target based on it.

    let object = [
        "key": {
               login-attempt: 1
               name: "ADMIN"
               phone: "0777123456"
            }]

what i have tried is below

object[0].substr(0,2); 

2 Answers2

2

let test = {
        key: {
               "login-attempt": 1,
               name: "ADMIN",
               phone: "0777123456",
          }
     };
            
console.log(test.key.phone.substr(0,2)); 
marzzy
  • 706
  • 10
  • 21
1

You're more likely to have an object like this:

let object = {
  login-attempt: 1
  name: "ADMIN"
  phone: "0777123456"
};

In this case, your code might be:

let prefix = object.phone.substr(0,2);

Or you might have an array of objects:

let object = [
  {
    login-attempt: 1
    name: "ADMIN"
    phone: "0777123456"
  },
  {
    login-attempt: 1
    name: "CLERK"
    phone: "2222222222"
  }
];

You can get the 1st two characters of the second element like this:

let prefix = object[1].phone.substr(0,2);

If the element was nested within "key":

let object = {
  key: {
    login-attempt: 1
    name: "ADMIN"
    phone: "0777123456"
  }
};

let prefix = object.key.phone.substr(0,2);

And so on...

paulsm4
  • 114,292
  • 17
  • 138
  • 190