Как получить инициалы имени из объекта - PullRequest
0 голосов
/ 07 февраля 2019

Мой код не работает.Мне нужна обратная связь и эффективный способ вернуть инициалы имени и фамилии, которые соответствуют идентификатору, переданному в функцию.

var contactList = [
    {
    "id": 'e3d46de8c7194cb1a32275195c15dc07',
    "name": 'Niels Bohr',
    "num_messages": 62,
    },
    {
    'id': '7064c3f9c99743b2838bbd8eacafe0d6',
    "name": 'Max Planck',
    "num_messages": 15,
    },
    {
    "id": 'b19e575a0d3f4151a1391452d8a47a44',
    "name": 'Jane Goodall',
    "num_messages": 20,
    },
    {
    "id": '17d9d0908f454253b5337e8c1ef4b564',
    "name": "Caroline Herschel",
    "num_messages": 3,
    },
]

function getInitials(id){
    // find the user object
    for (let u of contactList) {
        if (u["id"] == id){
            var initials = ''
            names = u.name.split(' ')
            for(var i; i < names.length; i++){
                initials += names[i][0]
            }
            // return the initials
            return initials
        }
    }
}

Ответы [ 7 ]

0 голосов
/ 07 февраля 2019

Вот краткий способ сделать это с filter, map, shift и регулярным выражением в одной цепочке операций.Техника будет работать с любым количеством пробелов, см. Пример ниже и вернет undefined, если идентификатор контакта не найден.

Сначала вы фильтруете массив для правильного идентификатора, это возвращает массив (может быть пустым), на котором вы отображаете, чтобы извлечь инициалы с String.match, регулярным выражением и Array.join.Затем вы сдвигаете первый элемент, чтобы получить результат, shift не вызовет ошибку, если элемента нет, и просто вернет undefined.

Вот два возможных регулярных выражения для извлечения инициалов:

  • /\b(\w)/g
  • /(?<=(\s+|^))(\w)/g

Первое регулярное выражение использует \b для сопоставления границ слова, тогда как \w будет соответствовать любому символу слова, поэтому регулярное выражение \b(\w) будет захватывать первый символ каждого слова.Это регулярное выражение не будет выполнено, когда имена разделены тире, так как тире будет считаться разделителем слов.

Второе регулярное выражение будет соответствовать каждому первому слову, используя положительный знак поиска за (?<=(\s+|^)), который проверяет пробелы илиначало строки.

const contactList = [{
  "id": 'e3d46de8c7194cb1a32275195c15dc07',
  "name": '   Niels        Bohr',
  "num_messages": 62,
}, {
  'id': '7064c3f9c99743b2838bbd8eacafe0d6',
  "name": 'Max Planck    ',
  "num_messages": 15,
}, {
  "id": 'b19e575a0d3f4151a1391452d8a47a44',
  "name": '  Jane Goodall',
  "num_messages": 20,
}, {
  "id": '17d9d0908f454253b5337e8c1ef4b564',
  "name": "Caroline Herschel",
  "num_messages": 3,
}];

function getInitials(id) {
  return contactList
    .filter(contact => contact.id === id)
    .map(contact => contact.name.match(/(?<=(\s+|^))(\w)/g).join(''))
    .shift();
}

console.log(getInitials('17d9d0908f454253b5337e8c1ef4b564'));
console.log(getInitials('b19e575a0d3f4151a1391452d8a47a44'));
console.log(getInitials('7064c3f9c99743b2838bbd8eacafe0d6'));
console.log(getInitials('e3d46de8c7194cb1a32275195c15dc07'));
console.log(getInitials('123'));
0 голосов
/ 07 февраля 2019
    You have bag :
    ` for(var i; i < names.length; i++){
       initials += names[i][0]
      } `   
     1.i have to be initelased var i = 0;            

, кроме того, ваш код работает

0 голосов
/ 07 февраля 2019

Простой однострочный подход с использованием Array.reduce и Array.find Эта функция вернет неопределенное значение, если идентификатор не указан.

var contactList = [
    {
    "id": 'e3d46de8c7194cb1a32275195c15dc07',
    "name": 'Niels Bohr',
    "num_messages": 62,
    },
    {
    'id': '7064c3f9c99743b2838bbd8eacafe0d6',
    "name": 'Max Planck',
    "num_messages": 15,
    },
    {
    "id": 'b19e575a0d3f4151a1391452d8a47a44',
    "name": 'Jane Goodall',
    "num_messages": 20,
    },
    {
    "id": '17d9d0908f454253b5337e8c1ef4b564',
    "name": "Caroline Herschel",
    "num_messages": 3,
    },
]

function getInitials(id){
  //using .find to find the element in the array
  const contact = contactList.find(contact => contact.id === id) 
  //cross checking if id is present and for that id name key is present and then using reduce function to get initials.
  return contact && contact.name && contact.name.split(' ').reduce((initial, name) => initial + name[0], '')
}

console.log(getInitials('b19e575a0d3f4151a1391452d8a47a44'))  //JG

console.log(getInitials('random'))  //undefined
0 голосов
/ 07 февраля 2019

Прежде всего найдите предмет, для которого id соответствует заданному id, используя find () .Затем split() его name и сопоставьте его с name[0], а затем join()

var contactList = [
    {
    "id": 'e3d46de8c7194cb1a32275195c15dc07',
    "name": 'Niels Bohr',
    "num_messages": 62,
    },
    {
    'id': '7064c3f9c99743b2838bbd8eacafe0d6',
    "name": 'Max Planck',
    "num_messages": 15,
    },
    {
    "id": 'b19e575a0d3f4151a1391452d8a47a44',
    "name": 'Jane Goodall',
    "num_messages": 20,
    },
    {
    "id": '17d9d0908f454253b5337e8c1ef4b564',
    "name": "Caroline Herschel",
    "num_messages": 3,
    },
]
function getInitials(id){
    let obj = contactList.find(item => item.id === id);
	return obj && obj.name.split(' ').map(a => a[0]).join('');
}
console.log(getInitials('7064c3f9c99743b2838bbd8eacafe0d6'))
console.log(getInitials('17d9d0908f454253b5337e8c1ef4b564'))
console.log(getInitials('b19e575a0d3f4151a1391452d8a47a44'))
console.log(getInitials('0'))
0 голосов
/ 07 февраля 2019

Вы можете найти объект, получить имя и построить инициалы.

function getInitials(array, id) {
    var temp = array.find(o => o.id === id);
    return temp && temp.name.split(' ').map(([c]) => c).join('');
}

var contactList = [{ id: 'e3d46de8c7194cb1a32275195c15dc07', name: 'Niels Bohr', num_messages: 62 }, { id: '7064c3f9c99743b2838bbd8eacafe0d6', name: 'Max Planck', num_messages: 15 }, { id: 'b19e575a0d3f4151a1391452d8a47a44', name: 'Jane Goodall', num_messages: 20 }, { id: '17d9d0908f454253b5337e8c1ef4b564', name: "Caroline Herschel", num_messages: 3 }];

console.log(getInitials(contactList, 'b19e575a0d3f4151a1391452d8a47a44'));
console.log(getInitials(contactList, '000'));
0 голосов
/ 07 февраля 2019

попробуйте это, может быть, вам нужно?

var contactList = [
    {
    "id": 'e3d46de8c7194cb1a32275195c15dc07',
    "name": 'Niels Bohr',
    "num_messages": 62,
    },
    {
    'id': '7064c3f9c99743b2838bbd8eacafe0d6',
    "name": 'Max Planck',
    "num_messages": 15,
    },
    {
    "id": 'b19e575a0d3f4151a1391452d8a47a44',
    "name": 'Jane Goodall',
    "num_messages": 20,
    },
    {
    "id": '17d9d0908f454253b5337e8c1ef4b564',
    "name": "Caroline Herschel",
    "num_messages": 3,
    },
]

function getInitials(id){
    // find the user object
    for (let u of contactList) {
        if (u["id"] == id){
            var initials = ''
            names = u.name.split(' ')
            console.log(names.length);
            for(var i=0; i< names.length; i++){
            
              initials+=' ' + names[i].charAt(0);
            }
            // return the initials
            console.log(initials, 'pop');
            return initials
        }
    }
}
getInitials('17d9d0908f454253b5337e8c1ef4b564');
0 голосов
/ 07 февраля 2019

Вы можете попробовать ниже код

var contactList = [
    {
    "id": 'e3d46de8c7194cb1a32275195c15dc07',
    "name": 'Niels Bohr',
    "num_messages": 62,
    },
    {
    'id': '7064c3f9c99743b2838bbd8eacafe0d6',
    "name": 'Max Planck',
    "num_messages": 15,
    },
    {
    "id": 'b19e575a0d3f4151a1391452d8a47a44',
    "name": 'Jane Goodall',
    "num_messages": 20,
    },
    {
    "id": '17d9d0908f454253b5337e8c1ef4b564',
    "name": "Caroline Herschel",
    "num_messages": 3,
    },
]

//here constant is your id which you passed in if condition
var str = contactList.find(x => x.id =='17d9d0908f454253b5337e8c1ef4b564').name.split(' ');
var result =""
for(var s of str)
   result += s.substr(0, 1)
   
console.log("Initals of \""+str+"\" is " + result);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...