Search for a value within an object in javascript [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have an array within an angular scope that basically contains an object within each iteration. I have used the indexOf() function before to check if a value exists within an array - but how can I check if a value exists within the object word value?
I want to use a foreach loop and just check if a word exists within the rules array in the format shown below - how is the best way to achieve this?
rules = [];
rules[0] = { word:"house"}
rules[1] = { word:"shoes"}
rules[2] = { word:"tools"}

rules = []
rules[0] = { word:"house"}
rules[1] = { word:"shoes"}
rules[2] = { word:"tools"}
rules[3] = { sentence:"horse"}
rules.forEach(rule => {
if (rule.word) {
console.log('Exist. Value:', rule.word)
} else {
console.log('Doesn\'t Exist.')
}
})
Hope this helps!

for(var i =0;i < rules.length;i++){
if(rules[i].word === 'valueYouWantToCheck'){
// do whatever you want to do
}
}
Try this...:)

You can use this
var rules = [];
rules[0] = { word:"house"}
rules[1] = { word:"shoes"}
rules[2] = { word:"tools"}
rules.forEach(function(item){
console.log(item.word) // your word of choice
})
You can also use filter function. If your required word is matched it will return the object or else it will return an empty array
var getValue = rules.filter(function(item){
return item.word=='house';
})
console.log(getValue)
Beside you can also use .find method
rules.find(function(item){
return item.word=="house";
})

rules = [];
rules[0] = { word:"house"}
rules[1] = { word:"shoes"}
rules[2] = { word:"tools"}
for(var i=0; i<rules.length ; i++)
{
rules[i]["word"]=='valueforComparison'; // or rules[i].word=='valueforComparison';
}

Related

How To Do This in JavaScript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
var sunny=[1,2,3];
var bunny=[4,5,6];
var name=prompt("Enter Name");
for(var i=0;i<3;i++)
{
document.write(name[i]);
}
//If User input Sunny then array elements of sunny will be printed.
You can use object for users and write your users in it, example:
var users = {
sunny: [1,2,3],
bunny: [4,5,6]
}
var name = prompt("Enter Name");
console.log(users[name]);
//If User input Sunny then array elements of sunny will be printed.
I think what you want is to use an object:
const names = {
sunny:[1,2,3],
bunny:[4,5,6],
};
const name=prompt("Enter Name");
for(var i=0;i<3;i++)
{
document.write(names[name][i]);
}
There is not clean way to get a variable if you have its name as string. However its easy to access an objects properties with a string with the [] syntax.
U can achieve this by using 'eval'.
See the update code.
var sunny=[1,2,3];
var bunny=[4,5,6];
var name=prompt("Enter Name");
for(var i=0;i<3;i++)
{
document.write(eval(name)[i]);
}
You can use a switch-statement (https://www.w3schools.com/js/js_switch.asp) like
var a;
switch(name) {
case "sunny":
a = sunny;
break;
case "bunny":
a = bunny;
break;
}
for(var i = 0; i < a.length; i++) {
document.write(a[i]);
}

Construct a selector with if statements in JavaScript [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I create a MongoDB selector from some session variables. If the session value is null, the selector should not include the condition.
I have a selector
return Session.get('title') ? { title: Session.get('title') } : {};
which works as it should; however, I want to filter on more session values.
If I add another one, I get
var title = Session.get('title');
var age = Session.get('age');
if (title && age) {
return {
title: title,
age: age
};
} else if (title) {
return {
title: title
};
} else if (age) {
return {
age: age
}
} else {
return {}
}
and it will only get more complicated when I add another session value.
How can I obtain the same result in a smarter way?
You could use an array to hold all of your possible values, then you just add to this array when a new value is added.
var sessionVars = ['title', 'age'];
var result = {};
sessionVars.forEach(function(varName) {
var value = Session.get(varName);
if (value) {
result[varName] = value;
}
});
return result;

Create new objects inside of a function with JavaScript?

So I want to create a function that if, if a question is answered wrong, it stores the wrong answer into a new object? So that I can list all of the wrong answers at the end?
var answerList = [{question:1, answer:1},{question:2, answer:2},]
var listofWrongAnswers = [];
if (answerSelected != answerlist[1].answer) {
/* create a new object
put answerlist[1].question and answerlist[i].answer in new object and push to
array ListofWrongAnswers */
}
I dont get how you can randomly name variables? if that's even possible.
Couldn't you simply create a new object based on the current question?
Something like this should work:
if (answerSelected != answerlist[1].answer) {
listofWrongAnswers.push({question: answerlist[1].question, answer: answerlist[1].answer});
}
However, you should look to make that index a parameter:
function addToWrongAnswers(answerSelected, idx) {
if (answerSelected != answerlist[idx].answer) {
listofWrongAnswers.push({question: answerlist[idx].question, answer: answerlist[idx].answer});
}
}
I assume you want something like this:
function getQuestion(number){
for(var i = 0; i < answerList.length; i++){
if(answerList[i].question === number){
return answerList[i];
}
}
}
function checkAnswer(questionNumber, answer){
var question = getQuestion(questionNumber);
if(answer !== question.answer){
listofWrongAnswers[question];
}
}
However, I'm also assuming you'll start with Question 1 and increment the number, so it would be even simpler if you just selected the question using an array index, rather than iterating through it. So this might be better:
var answerList = [{question:1, answer:1}, {question:2, answer:2}];
var listofWrongAnswers = [];
function checkAnswer(questionNumber, answer){
var question = answerList[questionNumber - 1];
if(answer !== question.answer){
listofWrongAnswers[question];
}
}
If you want to clone that question object and push it into that array, you can use
listofWrongAnswer.push({question: answerlist[1].question, answer: answerlist[1].answer});
But with this code you won't can use == operator to compare question objects existing at those arrays
listofWrongAnswer[1] == answerlist[1] // It's false
But if you don't want such a behavior you can store only references to question objects in the wrong answer list:
listofWrongAnswer.push(answerlist[1]);
With this code you can compare question objects with == operator
listofWrongAnswer[1] == answerlist[1] // It's true

What is the difference between `for` and `while` loops in my Script [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a JavaScript function that collects a number of input tags into an array and then decides if one of them has been selected:
function validateAnswerSelected () {
var formValid = false;
var groupedInput = document.getElementsByName("choice");
var i;
// while (!formValid && i < questions[questionNumber].choices.length) {
// if (groupedInput[i].checked) {
// formValid = true;
// }
// i++;
// }
// for (i = 0; questions[questionNumber].choices.length; i++) {
// if (groupedInput[i].checked) {
// formValid = true;
// }
// }
if (!formValid) {
alert("select an answer");
}
}
When I uncomment the while loop the function works correctly. However when I uncomment the for loop groupedInput becomes undefined.
What is the difference here?
Edit: when I uncomment the while then I do initialise the i variable. The error I made in the question is just a typo.
Typo:
for (i = 0; questions[questionNumber].choices.length; i++) {
Should be:
for (i = 0; i < questions[questionNumber].choices.length; i++) {
// ^ You forgot the `i <`
You didn't assign a value for "i" before using a while loop.
Blockquote var i; //default is undefined
But, in for loop you have assigned inside of that.
Blockquote for (i = 0; questions[questionNumber].choices.length; i++) {
That's why it returns undefined.
Sollution:
var i = 0;
Now it works fine. :)

What is the best way to call a function that receives single objects as argument when you have collections instead? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Sometimes you have a function that will work for flat arguments. For example:
send(player,message)
But what if, instead, you have collections of players / messages?
message = ['Welcome!','Check our site for events.']
players = [Player1,Player2,Player3]
Writting for-loops will reduce readability and won't work if you don't know statically if your argument is a collection or object. Rewritting the function is sometimes not viable or too laborous and promotes duplicate code. What is a simplier solution?
You can write a decorator that will transform your function into a function that will take the cartesian product of it's own arguments and call the original function on it.
function send(player,message) {
console.log('To ',player,': ',message);
}
cartesian(send)(['Player1','Player2','Player3'],['Welcome!','Check our site.']);
//Output:
//To Player1 : Welcome!
//To Player1 : Check our site.
//To Player2 : Welcome!
//To Player2 : Check our site.
//To Player3 : Welcome!
//To Player3 : Check our site.
This implements the decorator ("cartesian") on Javascript:
function cartesian_product(arr){
//cartesian_product( [[1,2],[3,4]] ) = [[1,3],[1,3],[2,3],[2,4]]
function partial_product(arr,i){
//partial_product([[1,2],3],0) = [[1,3],[2,3]]
var result = []
for (j=0; j<arr[i].length; ++j){
arr_changed = arr.slice();
arr_changed.splice(i,1,arr[i][j]);
result.push(arr_changed);
};
return result;
};
var result = [arr.slice()];
for (var x=0; x<arr.length; ++x){
for (var y=0; y<result.length; ++y){
if (result[y][x] instanceof Array) {
result.splice.apply(result,[y,1].concat(partial_product(result[y],x)));
}
}
}
return result;
};
function cartesian(func){
//cartesian(func)([1,2],[3,4]) = [func([1,3]),func([1,4]),func([2,3]),func([2,4])]
_this = this;
return function(){
var args_list = cartesian_product(Array.prototype.slice.call(arguments));
var return_values = []
for (var i=0; i<args_list.length; ++i){
return_values.push(func.apply(_this,args_list[i]))
}
return return_values;
}
}

Categories

Resources