Leo Messi
Leo Messi

Reputation: 6166

Check if an element is a property of an object into an array

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 valueproperty 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

Answers (3)

gurvinder372
gurvinder372

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

Titus
Titus

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

31piy
31piy

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

Related Questions