I've got some JSON data in which I'm trying to check if a key is contained in the entire array and add a class or do something else. If there is one key contained in the array I want to perform an action otherwise if there is no key do something. I've been banging my head for hours ,inArray doesn't seem to be working for me or hasOwnProperty. I've got to be doing something stupid simple wrong here. Kind of a newb so please include code samples were applicable.
JS Fiddle: http://jsfiddle.net/AtC4G/
var data={"users":[
{
"firstName":"Ray",
"lastName":"Villalobos",
"userName":"rvilla",
"joined": {
"month":"January",
"day":12,
"year":2012
}
},
{
"firstName":"John",
"lastName":"Jones",
"joined": {
"month":"April",
"day":28,
"year":2010
}
},
{
"firstName":"John",
"lastName":"Johnson",
"userName": "jjoe"
}
]}
if($.inArray('userName', data.users) == -1) { alert('not in array'); }
if(data.users.hasOwnProperty('userName')){
alert('do something');
}
The [ indicates an array, so you need to treat it as an array (data.users[0], not just data.users):
if($.inArray('userName', data.users[0]) == -1) { alert('not in array'); }
if(data.users[0].hasOwnProperty('userName')){
alert('do something');
}
you can compare a variable with a undefined value
for(user_index in data.users){
user=data['users'][user_index];
if(user.userName==undefined){
alert('username undefined in user '+user.firstName+' '+user.lastName);
}
}
To find out, whether a property is set, I would go for a native JS.solution:
function containsKey(key){ return function(el){
return el[key]!==undefined;
}};
containsUserName=containsKey("userName");
console.log(data.users.some(containsUserName))
This is all you need.
containsKey is a closure, which saves the key, for which you are looking for.
containsUsername is the function, which is used to look for a specific property.
Read the MDN documentation of Array.some() for compatibility etc.
Here is a Fiddle to play with.
If you want to extract that element: Array.filter() might be of interest.
Related
So here is my current code for a currency system. This code works to add the new user information in. Obviously this will keep adding the people that are already in it.
if (!currency[message.author.id]) {
currency.push({id: message.author.id, coins: 0});
}
if I change it to this one, nothing happens. It seems there's something wrong with this comparison and I'm not sure what it is considering it worked for other things I have used.
if (!currency[0].id == message.author.id) {
currency.push({id: message.author.id, coins: 0});
}
This looks right to me as it's getting the id property of the first element and checking if they're the same. When I run the code it just doesn't do anything. No errors and nothing in the json file I'm using to store it. It does this when the array is empty and does it when I have an id property in there.
Is this not possible? I don't like having to set it up using the first way because I'd like to be able to access everyone's currency if needed to add or take away without having to do it one person at a time.
I think it should be !==:
if (currency[0].id !== message.author.id) {
currency.push({id: message.author.id, coins: 0});
}
or should be wrapped in brackets:
if (!(currency[0].id == message.author.id)) {
currency.push({id: message.author.id, coins: 0});
}
It sounds like you probably want a data structure that's an object, not an array, so that you can have arbitrary key-value pairs - have the key be the message.author.id.
const currency = {};
// ...
const { id } = message.author;
if (!currency[id]) {
currency[id] = { id, coins: 0 };
} else {
// this author was already inserted - do something else here, if desired
// current[id].coins += coinChangeAmount; // for example
}
Your original code sounds like it's misusing an array as an object, and the currency[0].id == message.author.id will only check the [0]th element of the array, rather than iterating over all possible elements and looking for an ID match.
Guys I want to get an element from array. Here:
Follower:
{ follower:
[ 5edfe8f3bfc9d677005d55ca,
5edfe92fbfc9d677005d55cc,
5ee2326cc7351c5bb0b75f1a ],
user id:
5edfe92fbfc9d677005d55cc
The process:
if(follower == user){
console.log("sdasdsad")
}else{
console.log("no")
}
But when I do it it always returns as no.
Also this is the codes of===> Nodejs Follow System Not Working Properly
It is a nodejs project. So please look at the above link.
When I do
if(follower.includes(user)){
It gives the error of:
TypeError: Cannot read property 'includes' of null
And when I try to change some I get this error:
TypeError: takip.includes is not a function
Guys so thats why I say please look at the above code.
So how to equalize them?
As other peoples said earlier the follower itself is a property which its value is an array itself, so if you want to check whether an item exists within it or not you can check it with includes(), if it exists it will return true otherwise it will return false.
const follow = {
follower: ["5edfe8f3bfc9d677005d55ca",
"5edfe92fbfc9d677005d55cc",
"5ee2326cc7351c5bb0b75f1a"
]
}
const user = "5edfe92fbfc9d677005d55cc";
if (follow.follower.includes(user)) {
console.log("sdasdsad")
} else {
console.log("no")
}
But if you looking to find the exact position of the item within that array you can find it with indexOf(). If the item does not exist within the array it will return -1, otherwise, it will return the index of that item within the array.
const follow = {
follower: ["5edfe8f3bfc9d677005d55ca",
"5edfe92fbfc9d677005d55cc",
"5ee2326cc7351c5bb0b75f1a"
]
}
const user = "5edfe92fbfc9d677005d55cc";
console.log(follow.follower.indexOf(user));
You are trying to compare a string to an array so it will never pass the if statement.
If you change your if to be if ( follower.includes(user)) { then it will search the array for the string.
var follower = [
'5edfe8f3bfc9d677005d55ca',
'5edfe92fbfc9d677005d55cc',
'5ee2326cc7351c5bb0b75f1a'
]
var user = '5edfe92fbfc9d677005d55cc'
// This will always fail as follower is an array not a string
if (follower.includes(user)){
console.log("sdasdsad")
} else {
console.log("no")
}
References
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
Looks like follower is a property. You can use this solution:
objectName.follower.forEach(item =>
if (item == user) console.log(`${item} is the answer`);
);
This way, javascript will go through all of the elements in the array and print it out if it is matching with your user variable.
You can also use for loop or while loop for the same process, however, since you're using an array, forEach will be much more useful.
If this was not your question and I misunderstood your question, let me know, I'll see if I can help.
I hope this helps
var obj = {
follower: [ '5edfe8f3bfc9d677005d55ca',
'5edfe92fbfc9d677005d55cc',
'5ee2326cc7351c5bb0b75f1a'
]
};
var userId = '5edfe92fbfc9d677005d55cc';
function searchUser(object, user){
if(obj.follower.includes(user)){
return object.follower.filter(x => x == user);
} else {
return 'no';
}
};
console.log(searchUser(obj, userId));
You can use Array.protorype.some() to check if user exists in the follower array.
const obj = {
follower: [
"5edfe8f3bfc9d677005d55ca",
"5edfe92fbfc9d677005d55cc",
"5ee2326cc7351c5bb0b75f1a"
]
}
const user = "5edfe92fbfc9d677005d55cc";
if(obj.follower.some(item => item === user)) {
console.log("found")
} else{
console.log("no")
}
You can also get the item with Array.protorype.find() with the same way as above, just assign it to a variable
Array.prototype.some
Array.prototype.find
I have an array that looks something like this.
Users : {
0 : { BidderBadge: "somestuff", Bidders: 6, }
1 : { BidderBadge: "somemorestuff", Bidders: 7,}
}
I want to search the array using lodash to find a value inside of each of the user objects.
Specifically, I want to use values from another similar array of objects to find the value.
var bidArray = [];
_.each(this.vue.AllUsers, function(user) {
_.each(this.vue.Bids, function(bid) {
if(user.BidderBadge == bid.Badge) {
bidArray.push(user);
}
});
});
This is what I have and it works, but I want to do it using only one loop instead of two. I want to use something like _.indexOf. Is that possible?
If you want to avoid nesting, you just have to modify Azamantes' solution a bit
var bidders = this.vue.Bids.reduce(function(acc, bid) {
return acc[bid.BidderBadge] = true;
}, {});
var bidArray = this.vue.AllBidders.filter(function(bidder) {
return !!bidders[bidder.Badge];
});
It is difficult to give an accurate answer with an example that doesn't coincide with the input that your provide.
Anyway, supposing your data structures were more or less like this ones, you could solve the problem with lodash _.intersectionWith.
Intersect both arrays using a comparator that checks the correct object properties. Also, take into account that users must go first in the intersection due to the fact that you're interested in its values.
function comparator(user, bid) {
return user.BidderBadge === bid.Badge;
}
console.log(_.intersectionWith(users, bids, comparator));
Here's the fiddle.
i have a object, just i need to collect and store the object which contains the lable as link in to a new array.. can any one give me the best way to do this?
myobeject:
var xploreMaps = {
radious:55,
stroke:5,strokeColor:'#fff',
opacity:0.8,fontSize:13,line:10,
cRtext:{
length:4,
lineColor:'#7d2c2c',
prop:{
0:{link:'motionGraphics.html',color:'#595959',text:'Motion Graphics'},
1:{link:'video.html',color:'#306465',text:'Video'},
2:{link:'photography.html',color:'#7e6931',text:'Photography'},
3:{link:'copyRight.html',color:'#4c4966',text:'Copywriting'}
}
},
cBtext:{
length:3,
lineColor:'#4c839d',
prop:{
0:{link:'imagination.html',color:'#595959',text:'Imagination'},
1:{link:'innovation.html',color:'#306465',text:'Innovation'},
2:{link:'ideation.html',color:'#7e6931',text:'Ideation'}
}
},
cGtext:{
length:5,
lineColor:'#579549',
prop:{
0:{link:'catalogs .html',color:'#7a5967',text:'Catalogs',
subLink:{0:{link:'SEO_SMM.html',color:'#4e4b69',text:'SEO/SMM',align:'top'},1:{link:'site_analytics.html',color:'#545454',text:'Site analytics',align:'btm'}}},
1:{link:'socialmedia.html',color:'#1e9ead',text:'Innovation'},
2:{link:'loyalty .html',color:'#8fad34',text:'Ideation'},
3:{link:'promotions .html',color:'#563b64',text:'Promotions'},
4:{link:'implementations.html',color:'#2c6566',text:'Implementations',
subLink:{0:{link:'integrating.html',color:'#4c4a66',text:'Integrating',align:'top'},1:{link:'payment.html',color:'#948048',text:'Payment',align:'btm'}}}
}
}
}
My function which i try:
var links = []//just i need all the objects which contains the link.
var objFinder = function (obj){
$.each(obj,function(key,val){
if(key == 'link' && typeof val == 'string'){
links.push(val)
}else{
objFinder(val);//throws errors;
}
})
}
objFinder(xploreMaps);
}
I think the main issue is that your objects have a property length. That is messing up the processing. See the fiddle I created here:
http://jsfiddle.net/8Zfdj/
I just commented out the length property and it seems to work properly. I also did some minor cleanup such as adding missing semi-colons but that wasn't the main issue.
You can see the jQuery bug (invalid) here:
http://bugs.jquery.com/ticket/7260
In a JQuery getJSON call, how can I tell the length of the JSON that's returned?
function refreshRoomList() {
$.getJSON('API/list_rooms',
function (rooms) {
if (rooms.length > 0) {
$("#existing-room-list").empty();
$("#join-existing-room").text("Join existing room:"); // this shouldn't be here
$.each(rooms, function (index, roomName) {
var newChild = sprintf('<li>%s</li>', index, roomName);
$("#existing-room-list").append(newChild);
});
}
else {
$("#join-existing-room").text("No rooms found.");
}
});
}
For some reason this doesn't work, but if I replace rooms.length > 0 with true, the full list of rooms is printed out.
If rooms is empty, it is returned as {}.
If rooms is empty, it is returned as {}.
Thus, it's not an array, but an object. Objects doesn't have a length. There's only one of it. If you want to denote nothing, then rather use null instead of {}. This way you can use if (rooms) instead.
To learn more about JSON, you may find this article useful.
Try this approach instead, in your situation it should be null when empty:
if (rooms) {