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?
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'));
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" ) );
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.