[英]Check if an element is a property of an object into an array
I have a variable, for example myVariable.value = "text"
我有一个变量,例如
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. 我想找出
myVariable.value
是否可用作数组中对象的value
属性,没有别的。 Just get true if it is or false if it isn't in the array. 如果为true,则为true;如果不在数组中,则为false。
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. 您可以使用
Array#some
在数组中查找值。
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.
如果为true,则为true;如果不在数组中,则为false。
but I don't know how to do it for an array of objects.
但我不知道如何对一组对象执行此操作。 Any suggestions?
有什么建议么?
Use some
and includes
使用
some
和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: 您可以将数组
find
功能用于此类操作,这是一个示例:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.