-1
 let obj = [
    {
        name: 'jame',
        phone: 123456
    },
    {
        name: 'alex',
        phone: 456789
    }
]  
  

i'm creating app manager contact include functions .

  1. Input contact
  2. Delete contact
  3. Change contact
  4. Find contact
  5. Save and Exit
    help me part 4
Community
  • 1
  • 1

3 Answers3

-1

You need to iterate the Array (or use find or findIndex) and check phone key.

Search with String.prototype.includes()

You need to convert the search string and key value to lower/upper case to make it case insensitive search.

A sample code would look like this. (Please note that this returns the first match, if you need full list use filter, see other answers.)

let obj = [{
    name: 'jame',
    phone: 123456
  },
  {
    name: 'alex',
    phone: 456789
  }
];

function Search(arr, searchString, searchKey) {

  return arr.find((item) => String(item[searchKey]).toLowerCase().includes(searchString.toLowerCase()));

}

console.log(Search(obj, 'Lex', 'name'));

console.log(Search(obj, 'me', 'name'));

console.log(Search(obj, '89', 'phone'));
kiranvj
  • 32,342
  • 7
  • 71
  • 76
  • @KhoaVõĐức My solution returns the first match, to get all matches use `filter`. I am not adding filter in my solution as there are other solutions which uses `filter`. – kiranvj Apr 09 '20 at 07:40
-1

You could use filter method of array with String method includes.

let obj = [
    {
        name: 'jame',
        phone: 123456
    },
    {
        name: 'alex',
        phone: 456789
    }
]
function searchcontact(obj, query) {
    let searchTerm = String(query).toLocaleLowerCase();
    let result = obj.filter( item =>{
        if(item.name.toLocaleLowerCase().includes(searchTerm) || item.phone.toString().includes(searchTerm)) {
            return  item;
        }
    });
    return result;
}
console.log(searchcontact(obj, "jame"));
console.log(searchcontact(obj, "456"));
console.log(searchcontact(obj, "alex"));
Sohail Ashraf
  • 10,078
  • 2
  • 26
  • 42
-1

If I am not wrong you may want to search data from phone or email within an object in upper or lower case.

If that so then try below code call function on keypress or whatever event you like:

obj = [
{
  name : 'jame',
  phone : 123456
},
{
name : 'alex',
phone : 456789
}
]


var updateSearch = search => {

var  newObj = obj.filter(function (item) {
  let itemData = item.name ? item.name.toLowerCase() : ''.toLowerCase();
  let textData = search.toLowerCase();
  return itemData.indexOf(textData) > -1;

});


console.log(newObj);

};
niraj rahi
  • 57
  • 1
  • 5