0

I am trying to search with the word from the list of objects available in an array and it is available in all the objects then i should print a message as "Matched"

var objects = [
  {
    "foo" : "shaik",
    "bar" : "sit"
  },
  {
    "foo" : "lorem",
    "bar" : "ipsum"
  },
  {
    "foo" : "dolor",
    "bar" : "shaik"
  }
];

var results = [];

var toSearch = "shaik";

for(var i=0; i<objects.length; i++) {
  for(key in objects[i]) {
    if(objects[i][key].indexOf(toSearch)!=-1) {
      results.push(objects[i]);
    }
  }
}

gs.log(JSON.stringify(results));

Output:

*** Script: [{"foo":"shaik","bar":"sit"},{"foo":"dolor","bar":"shaik"}]

As of now with the above script i am able to display the matched objects but how to check like if it is available in all the objects then display Matched as result

Gordon Mohrin
  • 645
  • 1
  • 6
  • 17
Abdul Azeez
  • 63
  • 3
  • 9
  • Does this answer your question? [JS search in object values](https://stackoverflow.com/questions/8517089/js-search-in-object-values) – Ravi Makwana Jan 31 '20 at 06:19

2 Answers2

2

User every method to check. If the search word in exist all objects (any of the keys), Then print 'Matched'.

var objects = [
  {
    foo: "shaik",
    bar: "sit"
  },
  {
    random: "shaik",
    temp: "ipsum",
    some: "hello"
    
  },
  {
    foo: "dolor",
    bar: "shaik"
  }
];

var results = [];

var toSearch = "shaik";

if (objects.every((obj) => Object.values(obj).includes(toSearch))) {
  console.log("Matched");
} else {
  console.log("Not Matched");
}
Siva K V
  • 10,561
  • 2
  • 16
  • 29
0

This should do.

var objects = [
  {
    "foo" : "shaik",
    "bar" : "sit"
  },
  {
    "foo" : "lorem",
    "bar" : "ipsum"
  },
  {
    "foo" : "dolor",
    "bar" : "shaik"
  }
];

var results = [];

var toSearch = "shaik";

for(var i=0; i<objects.length; i++) {
  
    if(!(objects[i]['foo']==toSearch || objects[i]['bar']==toSearch)) {
      results.push(objects[i]);
  
  }
}

console.log(results);
ellipsis
  • 12,049
  • 2
  • 17
  • 33
  • I am getting the same result. My requirement is if shaik is not available in all the objects then i need to set console.log as Not Matched if shaik is available in all the objects then i should console the log as Matched – Abdul Azeez Jan 31 '20 at 06:22