Reputation: 41
This is my array:
const ids = [
"id1",
"id2",
"id3"
]
Object that is extracted via cookies
const data = [
{
id: "id3" // dynamically populated and can vary, we need this property
prop2: "prop2", // not needed
prop3: "prop3" // not needed
}
]
How can I compare first array values - ids
with data.id
, and if true
, show some logic (for example - console.log(true)
? I need it in if statement
.
Please note that data.id
. can be anything, from id1
to id3
. I need to find a way to dynamically compare these values. In "real world" it id anything from 1
do 50000
, but this is just a mock-up for the example.
Also I would appreciate Lodash example.
Upvotes: 1
Views: 69
Reputation: 390
Just run the next code:
<html>
<body>
<button onclick="compareIds()">Click me</button>
<script>
const ids = [
"id1",
"id2",
"id3"
]
const data = [
{
id: "id3", // dynamically populated and can vary, we need this property
prop2: "prop2", // not needed
prop3: "prop3" // not needed
}
]
function compareIds(){
var dataObject = findDataInObject();
for(var i = 0; i < ids.length; i++){
if (ids[i] == dataObject){
console.log("true");
}
else{
if(i == ids.length -1){
console.log("false");
}
}
}
}
function findDataInObject(){
for(key in data) {
if(data.hasOwnProperty(key)) {
var ArrayOfData = data[key];
var IdOfData = ArrayOfData.id;
return IdOfData;
}
}
}
</script>
</body>
Upvotes: 0
Reputation: 120
For each item in data, you check if the id is in the array of ids, and if yes, do something
const ids = [
"id1",
"id2",
"id3"
]
const data = [
{
id: "id3", // dynamically populated and can vary, we need this property
prop2: "prop2", // not needed
prop3: "prop3" // not needed
}
]
// if we have the id in ids array, do something
if (data.some(d => ids.indexOf(d.id) > -1)) {
// do something
}
Using lodash:
const ids = [
"id1",
"id2",
"id3"
]
const data = [
{
id: "id3", // dynamically populated and can vary, we need this property
prop2: "prop2", // not needed
prop3: "prop3" // not needed
}
]
// if we have the id in ids array, do something
if (_.some(data, d => ids.indexOf(d.id) > -1)) {
// do something
}
Upvotes: 0
Reputation: 36609
You can iterate all the elements in Array which are objects and using Object.keys
, iterate all the keys in that object which could be compared with initial array of values.
const ids = [
"id1",
"id2",
"id3"
];
const data = [{
id: "id3", // dynamically populated and can vary, we need this property
prop2: "prop2", // not needed
prop3: "prop3" // not needed
}];
const foundElems = [];
data.forEach((el) => {
Object.keys(el).forEach(elem => {
if (ids.indexOf(el[elem]) > -1) {
var Obj = {};
Obj[elem] = el[elem];
foundElems.push(Obj);
}
});
});
console.log(foundElems);
Upvotes: 1
Reputation: 4404
I think this is what you are looking for:
if (ids.indexOf(data.id) !== -1){
console.log('true')
}
Upvotes: 0