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

1

2 Answers 2

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");
}

Sign up to request clarification or add additional context in comments.

3 Comments

@Abdul, you need only result "Matched" or not right?
Yes, but as per your code we are hard coding to see 2 objects, i may n number objects for an example i have given 2 here
@AbdulAzeez, you mean more props other than foo, bar? I just updated answer for any number properties. this should work.
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);

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.