Am not able to add data to an array taken out from a cookie .
var x1 =[];
if($cookies.get(uid )== undefined)
{
var arr =[];
arr.push($scope.stock);
$cookies.put("arr",JSON.stringify(arr));
$cookies.put("uid","xxx");
console.log("==uid not found in cookie in angular --- cookies.uid"+ $cookies.get("arr"));
}
else
{
console.log("inside else"+JSON.stringify($cookies.getObject("arr"))); // gives output ["bse:yesbank"]
x1= JSON.stringify($cookies.getObject("arr"));
----> console.log(x1 instanceof Array); // returns false
----> x1.push($scope.stock);
}
it gives
x1.push is not a function
Moreover, it's says the JSON.stringify($cookies.getObject("arr")) is not an array but the value of above expression is ["bse:yesbank"] which is nothing but an array. please correct me where I am getting wrong .
That is because you use JSON.stringify, wich turns the array into a string looking like the array.
Try to get the value without stringify:
x1= JSON.stringify(["test"]);
console.log(x1 instanceof Array); // returns false
console.log(JSON.parse(x1) instanceof Array); // returns true
Related
For some reason when I try and call my command it returns [object Object],[object, Object]
fs.readFile(path.join(__dirname, "../moderation") + "/modlogs.json", "utf-8", function(err, data) { // read the JSON file
if (err) throw err; // throw error if applicable
var arrayOfObjects = JSON.parse(data); // parse the data
for (let i = 0; i < arrayOfObjects.warns.length; i++) { // loop through all keys in warns file
if (arrayOfObjects.warns[i].user_id === user.id) { // check if the user has already been warned
message.reply("User already warned. Kicking user."); // display kick
//message.guild.member(user).kick(); // kicks member
indexOfUser = arrayOfObjects.warns.findIndex(x => x.user_id == user.id); // find the index of the users object
//message.channel.sendMessage(indexOfUser);
message.channel.sendMessage("Before splicing" + arrayOfObjects.warns);
//arrayOfObjects.warns.splice(indexOfUser, 1); // remove the user from warns array
message.channel.sendMessage("After splicing" + arrayOfObjects.warns);
return;
};
};
The line //arrayOfObjects.warns.splice(indexOfUser, 1); // remove the user from warns array is supposed to delete that object from the warns array in my JSON file. However it doesn't, the console.logs were just to see what was getting outputed, and it seems like the values aren't getting through.
I think the problem is that you are using findIndex() instead indexOf() when you try to find the index.
Array.prototype.indexOf() expects a value as first parameter. This makes it a good choice to find the index in arrays of primitive types.
Array.prototype.findIndex() expects a callback as first parameter. Use this if you need the index in arrays with non-primitive types (e.g. objects) or your find condition is more complex than just a value.
See the links for examples of both cases.
info from this post
Edit:
I bring you some usefull code.
With indexOf()
if (arrayOfObjects.warns.indexOf(user_id) > -1) { // check if the user has already been warned
message.reply("User already warned. Kicking user."); // display kick
//message.guild.member(user).kick(); // kicks member
indexOfUser = arrayOfObjects.warns.indexOf(user_id);
//message.channel.sendMessage(indexOfUser);
message.channel.sendMessage("Before splicing" + arrayOfObjects.warns);
//arrayOfObjects.warns.splice(indexOfUser, 1); // remove the user from warns array
message.channel.sendMessage("After splicing" + arrayOfObjects.warns);
return;
};
Aclaration: indexOf(value) returns -1 if it can't find the item in the Array. Otherwise it returns the index where item is located. So you don't need to iterate in the array.
with findIndex()
When using findIndex() you don't define the value you want to find in the array. You define the function that will be executed every iteration.
You could do something like:
function iswarned (elem) {
return elem.user_id == user_id;
}
if (arrayOfObjects.warns.findIndex(iswarned) > -1) {
indexOfUser = arrayOfObjects.warns.findIndex(iswarned);
}
Aclaration: findIndex() returns the first index for what callback function returns a truthy value or -1 If the callback never returns a truthy value or array.length is 0.
I have a JSON object formatted like {"Foo": ["B","A","R"]}
I am trying to access the values of the array like this:
var json = '{"Foo": ["B","A","R"]}';
expression = JSON.Parse(json, function(key, value){
if(key == "Foo"){
console.log(value.length); // logs "3"
console.log(value[1]); // logs "undefined"
}
});
If I ask for the length of value it returns the correct length of the array, but if I ask for the value it returns undefined and I am not quite sure why.There are other values in the JSON that I am able to access just fine, but they are not arrays. Any insight would be appreciated. Thanks!
You should use JSON.parse like this:
var json = '{"Foo":["B","A","R"]}';
var object = JSON.parse(json);
// object is now and object containing the data from 'json'
var expression = object["Foo"][1]; // object["Foo"] refers to the
// value with key "Foo"
(Calling JSON.parse with a callback parameter is an advanced feature for transforming the JSON object, not reading it. In almost all cases, though, you want to use it like the above code, with no callbacks.)
As mentioned in another answer, if you simply want to retrieve the second element of Foo, you can do that easily enough after parsing using standard property access techniques such as obj.Foo[1].
Assuming you really want to use the optional second "reviver" parameter to JSON.parse, you need to return the value from the "reviver" callback;
expression = JSON.Parse(json, function(key, value){
if (key == "Foo"){
console.log(value[1]);
}
return value;
^^^^^^^^^^^^^
});
The reason it appears you can't access value[1] but you can access value.length is (as mentioned by user663031) you don't have a return value.
The reviver function replaces one value with another, if no return is specified all functions will return undefined. The order the reviver receives the values is: first each of the values in the array separately, then the array.
In your code each value has already been replaced with "undefined", so the array has three undefined values as reported by the length. value[1] really is returning the value at position 1 but it is set to "undefined".
When the json string has arrays the reviver function is called with index, [Object] as key, value parameters .
This sniped of code that filter object properties on parse phase will be helpful:
var json = '{"_embedded": [{"a":"A","b":"B","links": {"c":"C"}},{"a":"A2", "b":"B2","links": {"c":"C2"}}]}';
var schemaNames=["_embedded", "a"];
var result= JSON.parse(json, function(k, v) {
console.log(k,v);
if ("" === k){
return v;
}
// On arrays k is a number
else if (schemaNames.indexOf(k) > -1 || !isNaN(k)){
return v;
}
});
console.log(JSON.stringify(result));
Output: {"_embedded":[{"a":"A"},{"a":"A2"}]}
https://jsfiddle.net/pdorgambide/vphbmtk1/
use this code
var json = {'foo' : ['B', 'A', 'R']};
$.each(json, function(key, value){if(key == 'foo'){console.log(value[1]);}});
you already have a json object so no need to parse it again.
Suppose I have javascript class Connection and I have variable that should contain array of Connection object.
How to validate the variable?
[your array of Connection].every(elem => elem instanceof Connection);
It returns true if all items in your array are Connections, false otherwise
Function that checks your need
function isAllConnections(array) {
return array.every(function(elem) {
return elem instanceof Connection;
});
}
If you just want to check the variable exists and contains values:
var myArrayOfConnections = [];
if(myArrayOfConnections && myArrayOfConnections.length) {
//do stuff
}
The first check will evaluate whether it exists, second will check the length is greater than 0
First thing is to make sure the variable is Array:
Array.isArray( x );
function isArray(x) { return x.constructor.toString().indexOf("Array") > -1;}
x instanceof Array
Then you can check each element in the array:
for(var i in x) { if( x[i].isPrototypeOf(Connection) ) }
You might use instanceof. Without elaboration, your question is a bit unclear, but this may be useful:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FOperators%2Finstanceof
Assuming I have a Javascript array and some entries are defined as following:
arr["rrr"]=1;
arr["ee"]=2;
arr["qqq"]=22;
...
Let's assume one tries to retrieve an entry for an unexisting key, for example:
var retr = arr["ppp"];
What is the status of the retr var? Is it null or undefined or something else? How can I check whether the array did not contain a valid entry for the provided key? What is the proper test in Javascript? Thanks.
The result is undefined.
To test you just need to do this:
if ("ppp" in arr) {
// do something
} else {
// do something else
}
The value returned by a missing key is undefined. You can test if the key exists like this :
var a = [];
a.hasOwnProperty('k'); // false
The returned value of the undefined array keys is undefined. The proper test would be
var retr = arr["ppp"];
if(retr!=undefined){
//retr has some value
}
else{
//retr is undefined
}
I tried the code you wrote in Firebug. When I tried to access an entry for an unexisting key
var retr=arr["ppp"];
it returns null. Hence, retr is equal to null.
retr==null; //true
typeof retr=="undefined"; //true
I'm creating a JSON object like
tags = {"jon":["beef","pork"],"jane":["chicken","lamb"]};
which was generated using php from an array like
$arr = array(
'jon' => array('beef', 'pork'),
'jane' => array('chicken', 'lamb')
);
$tags = json_encode($arr);
And I want to check if something is in one or the other. None of these seem to work, but something like
if('lamb' in tags.jane)) {
console.log('YES');
} else {
console.log('NO');
}
writes NO to the console
if('foo' in tags.jane)) {
console.log('YES');
} else {
console.log('NO');
}
also writes NO to the console
so looking at
typeof(tags.jane);
it shows it's an "object" but
console.log(tags);
shows the following:
Object
jane: Array[2]
0: "chicken"
1: "lamb"
length: 2
__proto__: Array[0]
jon: Array[2]
0: "beef"
1: "pork"
length: 2
__proto__: Array[0]
__proto__: Object
so i thought maybe tags.jane may actually be an array and tried
if($.inArray('lamb', tags.jane)) {
console.log('YES');
} else {
console.log('NO');
}
which writes YES to the console but
if($.inArray('foo', tags.jane)) {
console.log('YES');
} else {
console.log('NO');
}
also writes YES to the console.
Am I incorrectly building the JSON Object? Not targeting the value(s) properly? Any advice is greatly appreciated. If this would be easier as an array instead of an object, I have full control to change it. I'm just a bit stumped at how I should treat this.
jQuery.inArray returns -1 when element is not found. That's true value from the POV of Javascript. Try this:
if($.inArray('foo', tags.jane) != -1) {
Your second set of answers are the way you should go. However, $.inArray returns an index, not a boolean. Any non-zero integer is true, which means when foo is not found, it returns -1 which evaluates to true and prints YES.
Similarly, $.inArray('chicken', tags.jane) would return 0 and cast to false, which is also not the answer you want.
Instead, use $.inArray('foo', tags.jane) !== -1 as your condition.
tags.name will give you the array for that person. So $.inArray("chicken",tags.jane) would see if "chicken" is in jane's tags array. If it's not, you'd get -1, otherwise you'd it's position in the array (using your example, this would return zero, the first array element).
You're using the keyword in for the wrong reason.
The statement ( prop 'in' obj ) checks to see if the object(associated array) has a property with the value of prop.
Since you're using the 'in' keyword on an array, then false is going to be returned because tags.jane is an array with indexes and not an associated array with properties.
If you want to know was values are in the array then loop through and compare.
If you want to use the 'in' keyword then convert your array to an object like so.
tags = {};
// old code
tags.jane = ['lamb', 'food'];
console.log(('lamb' in tags.jane) === false )
// new code
tags.jane = {
'lamb':1,
'food':1
}
console.log(('lamb' in tags.jane) === true )
https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...in
you can not use
if('foo' in tags.jane))
it should be used as
if (1 in tags.jane)
if you want to check 'foo' is in tags.jane, try this
var inIt = (function() {
var inIt = false;
tags.jane.forEach(function(item) {
inIt = inIt || 'foo' == item;
});
return inIt;
})();