Home > Blockchain >  how to return array of objects by checking string exists using javascript
how to return array of objects by checking string exists using javascript

Time:08-16

I have array of objects, in which the keys matches,

then return the array of object using javascript

for example,

Passing param zapp is found in arr, return those objects in array using

javascript

var arr =[
  {id:1, keys: "zapp"},
  {id:2, keys: "zapp, zoin"},
  {id:3, keys: "dell"}
];
tried

function checkKeys (arr, keytocheck) {
let result=[]
 if(arr.length > 0){
  for(let elem of arr) {
     const splitkeys = elem.keys(',');

     if(elem.keys.indexOf(',') > -1) {
      // comma have
      if(splitKeys.includes(keytocheck)){
       result.push(elem);
      }
     }
     else {
     // no comma
     if(elem.keys === keytocheck) {
     result.push(elem);
     }
    }
  }
 }
return result
};


console.log(checkKeys(arr, "zapp"));
Expected Output
[
{id:1, keys: "zapp"},
  {id:2, keys: "zapp, zoin"}
]


CodePudding user response:

You are missing split in:

const splitkeys = elem.keys(',');  // HERE keys is a string not a function

You have to use split here as:

const splitkeys = elem.keys.split(',');

var arr = [
    { id: 1, keys: 'zapp' },
    { id: 2, keys: 'zapp, zoin' },
    { id: 3, keys: 'dell' },
];

function checkKeys(arr, keytocheck) {
    let result = [];
    if (arr.length > 0) {
        for (let elem of arr) {
            const splitkeys = elem.keys.split(',');

            if (elem.keys.indexOf(',') > -1) {
                // comma have
                if (splitkeys.includes(keytocheck)) {
                    result.push(elem);
                }
            } else {
                // no comma
                if (elem.keys === keytocheck) {
                    result.push(elem);
                }
            }
        }
    }
    return result;
}

console.log(checkKeys(arr, 'zapp'));

ALTERNATE SOLUTION 1

You can use filter and includes here as:

var arr = [
    { id: 1, keys: 'zapp' },
    { id: 2, keys: 'zapp, zoin' },
    { id: 3, keys: 'dell' },
];

function checkKeys(arr, keytocheck) {
    return arr.filter((o) => o.keys.includes(keytocheck));
}

console.log(checkKeys(arr, 'zapp'));

ALTERNATE SOLUTION 2

You can use regex also here as:

var arr = [
    { id: 1, keys: 'zapp' },
    { id: 2, keys: 'zapp, zoin' },
    { id: 3, keys: 'dell' },
];

function checkKeys(arr, keytocheck) {
    const regex = new RegExp(keytocheck);
    return arr.filter((o) => o.keys.match(regex));
}

console.log(checkKeys(arr, 'zapp'));

CodePudding user response:

You can use filter method

const array = [
    { id: 1, keys: 'zapp' },
    { id: 2, keys: 'zapp, zoin' },
    { id: 3, keys: 'dell' },
];

function filterByKeyValue(arr, key){
   return arr.filter((el) => el.keys.toLowerCase().includes(key.toLowerCase()));
}

console.log(filterByKeyValue(array, 'zapp'));
  • Related