Reputation: 6166
I have a variable, for example myVariable.value = "text"
And an array of objects of this form:
[{name: "1", value: "word"},
{name: "2", value: "text"},
{name: "3", value: "xyz"}
]
I want to find out if myVariable.value
is available as a value
property of an object in the array, nothing else. Just get true if it is or false if it isn't in the array.
I found something here like:
var aa = {hello: "world"};
alert( aa["hello"] ); // popup box with "world"
alert( aa["goodbye"] ); // popup box with "undefined"
but I don't know how to do it for an array of objects. Any suggestions?
Upvotes: 0
Views: 48
Reputation: 68393
Just get true if it is or false if it isn't in the array.
but I don't know how to do it for an array of objects. Any suggestions?
Use some
and includes
var valueToFind = "text";
var isAvailable = arr.some( s => Object.values( s ).includes( valueToFind ) );
Demo
var arr = [{
name: "1",
value: "word"
},
{
name: "2",
value: "text"
},
{
name: "3",
value: "xyz"
}
];
var valueToFind = "text";
var isAvailable = arr.some( s => Object.values(s).includes( valueToFind ) );
console.log(isAvailable);
Convert this to a function
var fnCheckVal = ( arr, valueToFind ) => arr.some( s => Object.values(s).includes(valueToFind) );
console.log( fnCheckVal ( arr, "text" ) );
console.log( fnCheckVal ( arr, "word" ) );
Demo
var arr = [{
name: "1",
value: "word"
},
{
name: "2",
value: "text"
},
{
name: "3",
value: "xyz"
}
];
var fnCheckVal = ( arr, valueToFind ) => arr.some( s => Object.values(s).includes(valueToFind) );
console.log( fnCheckVal ( arr, "text" ) );
console.log( fnCheckVal ( arr, "word" ) );
console.log( fnCheckVal ( arr, "valueDoesn'tExists" ) );
Upvotes: 1
Reputation: 22474
You can use the array find
function for this kind of thing, here is an example:
var arr = [{name: "1", value: "word"},
{name: "2", value: "text"},
{name: "3", value: "xyz"}
];
var toFind = {value: "word"};
var foundObject = arr.find(v => v.value == toFind.value);
console.log(foundObject);
Upvotes: 1
Reputation: 23859
You can use Array#some
to find the value in the array.
let data = [{name: "1", value: "word"},
{name: "2", value: "text"},
{name: "3", value: "xyz"}
]
function findValue(value) {
return data.some(item => item.value === value);
}
console.log(findValue('text'));
console.log(findValue('another'));
Upvotes: 1