I need to access the id value in a Javascript object to display a simple message that the user has membership if the id value equals a specific value.
I'm getting Uncaught Type Error not defined 'id' message
In the console it's displayed as
subscriptions: Array(1)
0: // COMMENT Don't know what this is
autoRenew: false
canRenew: false
expiryDate: "2022-10-26T00:00:00"
membership:
id: "819AGBHDRLQHNHPHKKMPKLGPMDRDTDMVL"
I'm assuming equivalent JSON is something like:
subscriptions {
0
{
membership: {
id: "819AGBHDRLQHNHPHKKMPKLGPMDRDTDMVL"
}
}
}
My Javascript Code
const userObj3 = userObj['subscriptions']['0']['membership']['id'];
if (userObj3 = "819AGBHDRLQHNHPHKKMPKLGPMDRDTDMVL") {
greeting = "You have membership";
}
Your subscriptions are an array, also your comparison inside the if is incorrect and should be == or ===, you could also use dot annotation to traverse the object instead of using brackets on every key.
Using the index as a string instead of a number isn't really wrong, it's just not a good practice.
You might want to think about looping through the subscriptions instead of using the direct index just in case there's multiple subscriptions. But that just depends on how you structure your data and is kinda up to you.
const userObj = {
subscriptions: [
{
autoRenew: false,
canRenew: false,
expiryDate: '2022-10-26T00:00:00',
membership: {
id: '819AGBHDRLQHNHPHKKMPKLGPMDRDTDMVL'
}
},
{
autoRenew: true,
canRenew: false,
expiryDate: '2022-10-26T00:00:00',
membership: {
id: '201AGBHDRLQHNHPHKKMPKLGPMDRDTDMVL'
}
}
]
};
let greeting = "You're not a member";
userObj.subscriptions.forEach((sub) => {
if (sub.membership.id === '201AGBHDRLQHNHPHKKMPKLGPMDRDTDMVL') {
greeting = "You're a member";
}
});
console.log(greeting);
Related
I'm trying to come up with a method that would allow me to create a it block that confirms whether my configuration file has a specific attribute. The object has in it:
exports.config = {
services: [
['sauce', {
sauceConnect: true,
}]
],
}
I would like to have an it block that would confirm whether this value is true and if it isn't, then it should fail.
I have tried a couple approaches like if (sauceConnect in services) etc but it isn't an approach that is working. The test and the configuration file are in separated documents and for the life of me I can't work out a good enough test.
I'd appreciate any help or answers here.
On the assumption that this is how you want your config to look like, you'll have to loop through it and find the match:
const exportedConfig = {
services: [
['sauce', {
sauceConnect: true,
}],
['key', {
data: "value",
}]
],
}
// [1] refers to the 2nd element in the array, aka the value
// some looks for ANY match and if a match occurs it returns true.
console.log(exportedConfig.services.some(element => element[1].sauceConnect == true ))
Though, a recommendation would be to format your config as so:
const exportedConfig = {
services: {
sauce: {
sauceConnect: true,
},
key: {
data: "value",
}
},
}
``
I have type error. My variable creating this error while running with node.js. My variable is below. How can I describe my variable correctly ?
let allDevices = {
1: {
time: []
},
2: {
time: []
},
3: {
time: []
}
}
I'm guessing you're trying allDevices.1.time to get the above error message. With numeric object keys, you'd need to reference the numbered object keys using [] instead of . notation:
let allDevices = {
1: {
time: []
},
2: {
time: []
},
3: {
time: []
}
}
console.log(allDevices[1].time) // or allDevices['1'].time
You probably don't want that object structure, though; allDevices should probably just be an array, so you don't need to manage the index numbers manually. You'd access it the same way (but note that arrays are zero-indexed):
let allDevices = [
{
time: []
},
{
time: []
},
{
time: []
}
]
console.log(allDevices[0].time) // here, allDevices['1'] would not work; the index must be a number
If you are using the bracket notation already but still getting 'undefined' errors, check to make sure the data exists before you try accessing it; if allDevices is set up by something asynchronous you'll need to wait until that async call returns.
I am having a hard time filtering through an array of objects based on a value in a nested array of objects. I have a chat application where a component renders a list of chats that a user has. I want to be able to filter through the chats by name when a user types into an input element.
Here is an example of the array or initial state :
const chats= [
{
id: "1",
isGroupChat: true,
users: [
{
id: "123",
name: "Billy Bob",
verified: false
},
{
id: "456",
name: "Superman",
verified: true
}
]
},
{
id: "2",
isGroupChat: true,
users: [
{
id: "193",
name: "Johhny Dang",
verified: false
},
{
id: "496",
name: "Batman",
verified: true
}
]
}
];
I want to be able to search by the Users names, and if the name exists in one of the objects (chats) have the whole object returned.
Here is what I have tried with no results
const handleSearch = (e) => {
const filtered = chats.map((chat) =>
chat.users.filter((user) => user.name.includes(e.target.value))
);
console.log(filtered);
// prints an empty array on every key press
};
const handleSearch = (e) => {
const filtered = chats.filter((chat) =>
chat.users.filter((user) => user.name.includes(e.target.value))
);
console.log(filtered);
// prints both objects (chats) on every keypress
};
Expected Results
If the input value is "bat" I would expect the chat with Id of 2 to be returned
[{
id: "2",
isGroupChat: true,
users: [
{
id: "193",
name: "Johhny Dang",
verified: false
},
{
id: "496",
name: "Batman",
verified: true
}
]
}]
The second approach seems a little closer to what you're trying to accomplish. There's two problems you may still need to tackle:
Is the search within the name case insensitive? If not, you're not handling that.
The function being used by a filter call needs to return a boolean value. Your outer filter is returning all results due to the inner filter returning the array itself and not a boolean expression. Javascript is converting it to a "truthy" result.
The following code should correct both of those issues:
const filtered = chats.filter((chat) => {
const searchValue = e.target.value.toLowerCase();
return chat.users.filter((user) => user.name.toLowerCase().includes(searchValue)).length > 0;
});
The toLowerCase() calls can be removed if you want case sensitivity. The .length > 0 verifies that the inner filter found at least one user with the substring and therefore returns the entire chat objects in the outer filter call.
If you want to get object id 2 when entering bat you should transform to lowercase
const handleSearch = (e) =>
chats.filter(chat =>
chat.users.filter(user => user.name.toLowerCase().includes(e.target.value)).length
);
try this it should work
const handleSearch2 = (e) => {
const filtered = chats.filter((chat) =>
chat.users.some((user) => user.name.includes(e))
);
console.log(filtered);
};
filter needs a predicate as argument, or, in other words, a function that returns a boolean; here some returns a boolean.
Using map as first iteration is wrong because map creates an array with the same number of elements of the array that's been applied to.
Going the easy route, you can do this.
It will loop first over all the chats and then in every chat it will check to see if the one of the users' username contains the username passed to the function. If so, the chat will be added to the filtered list.
Note, I am using toLowerCase() in order to make the search non case sensitive, you can remove it to make it case sensitive.
const handleSearch = (username) => {
var filtered = [];
chats.forEach((chat) => {
chat.users.forEach((user) => {
if (user.name.toLowerCase().includes(username.toLowerCase())) {
filtered.push(chat);
}
});
});
console.log(filtered);
return filtered;
}
handleSearch('bat');
I have my object structured as below and I want to find the product with provided ID.
0 :{
id: 0,
title: 'xxxx',
url: "www.test.com"
quantity: 100
},
1 :{
id: 10,
title: 'xxxx',
url: "www.test.com"
quantity: 100
},
// and so on...
In order to search nested attribute within the object, I have written the below function:
export const selectProductById = (state, productId) => {
const obj_index = Object.keys(state.products).find(function(idx) {
if (state.products[idx].id == productId) {
return idx;
}
}
return state.products[obj_index]
}
This works but I will always get a warning during compilation of my react app.
Expected '===' and instead saw '=='
But if I change this into === the code will not work anymore, does anyone knows how to change this so that it follows JSLint rules ?
It sounds like the productId is not a number. Cast it to a number first:
if (state.products[idx].id === Number(productId)) {
But you should return a truthy or falsey value from the .find callback, not something that you're iterating over (since you may not be sure whether it's truthy or falsey, and it's potentially confusing). Return the result of the === comparison instead:
const { products } = state;
const obj_index = Object.keys(products).find(
key => products[key].id === Number(productId)
);
If I have the following object:
var record = {
title: "Hello",
children: [
{
title: "hello",
active: true
},
{
title: "bye",
active: false
}
};
I want to use underscore to determine if one of the children within the record has or does not have a title equal to a variable that will come from a form post, but also needs to be case insensitive... So for example:
var child = { title: "heLLo", active: true }
And underscore ( and this is wrong, and what I need help with ):
if ( _.contains(record.children, child.title) ) {
// it already exists...
} else {
// ok we can add this to the object
}
So basically I don't understand how to do this with underscore when dealing with array objects that have multiple key/value pairs. Also what is the best method for ignoring case? Should this be done in the underscore _.contains function? Regex? Use toLowerCase() beforehand to create the variables? If someone types in any variation of "Hello", "HELLO", "heLLO", etc. I don't want the insert to take place.
Thank you!
Use _.find and RegExp with "i" case-ignore flag
var valueFromPost = "bye";
var someOfChildrenHasValueFromPost = _.find(record.children,function(child){
return child.title.match(new RegExp(valueFromPost,"i"));
});
Update
Here is an example #JSFiddle
JS code:
record = {
children:[
{title:'bye'},
{title:'Bye'},
{title:'Hello'}
]
}
var testValue = function(value) {
return _.find(record.children,function(child){
return child.title.match(new RegExp(value,"i"));
});
}
console.debug(testValue('Bye')); //returns object with "Bye" title
console.debug(testValue('What'));//returns undefined
console.debug(testValue('bye')); //returns object with "bye" title