Finding a property in a JSON Object - javascript

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;
})();

Related

Object and array processing code not working

I'm trying to create a function called maybeNoises to test if an array has noises or not and then to print them to the console.
The prompt is as follow:
Function should take an object, if this object has a noises array return them as a string separated by a space, if there are no noises return 'there are no noises' (2, 1, 3)
This is my code:
function maybeNoises(object) {
if (object.noises) {
return object.noises.join(" ");
} else if (object["noises"].isArray(undefined)) {
console.log("THIS TEST IS STUPID AND PISSING ME OFF");
} else(object["noises"].isArray(null));
return 'there are no noises';
}
This is what it is testing:
QUnit.test("maybeNoises() : Should take an object, if this object has a noises array return them as a string separated by a space, if there are no noises return 'there are no noises'",
function(assert) {
assert.equal(maybeNoises({
noises: ["bark", "woof", "squeak", "growl"]
}), "bark woof squeak growl");
assert.equal(maybeNoises({
noises: []
}), "there are no noises");
assert.equal(maybeNoises({}), "there are no noises");
});
What am I doing wrong?
The issues with your code are
else(object["noises"].isArray(null)) isn't valid syntax
if (object.noises) return object.noises.join(" "); - your first test assumes that object has a property named noises, and that this noises object has a property called join which is a function ... that's a lot to assume without testing!!! ... what if noises is true for example, true doesn't have a join property! What if object is null/undefined? It doesn't even have a property called noises!
object["noises"].isArray(undefined) an array doesn't have a isArray function, only Array (literally, Array, not "an Array") has that function, and the argument to it should be the object you want to test
So, here's all you need to do
function maybeNoises(object) {
// we know nothing about object yet, so lets not assume
if (object && object.noises) { // check that object and object.noises are "something"
// here, we know that object.noises is "something"
if (Array.isArray(object.noises)) { // check that object.noises is an Array
// here we know that object.noises is an array, so, it has a length
if (object.noises.length > 0) { // check length is > 0
return object.noises.join(' ');
}
}
}
return 'there are no noises'; // didn't pass the above tests, so return this string
}
I edited my answer to summarize all the problems:
1.) Check if there is a noises array.
You wanna do Array.isArray(object.noises) or if you are in the unlikely event of this not working in your javascript implementation you can check for other alternatives here: Check if object is array?
2.) Check if the array has elements:
object.noises.length can be used to see if the array has any entries.
3.) Return the noises as array
You figured that out already correctly.

To check the JavaScript object has a value

Can you tell me how to check the JavaScript object has a value ? This vm.occupantDetail.contactDetail object is neither null nor undefined.It looks like as shown below at run time.
It defines as shown below.
vm.occupantDetail = {
contactDetail: {},
};
You can find the it using
Object.keys(vm.occupantDetail.contactDetail).length
It appears from your code that your vm.occupantDetail.contactDetail object is simply an empty object, and the __proto__ property that you are seeing is the protoype property of the Object. If you want to check if an object is null, the following conditional will do the job.
if (obj == null) { ... }
However, it appears that you want to check if an object is empty, which is different. If you want to check if a specified object has no assigned properties, try the following function.
function isEmpty(map) {
for(var key in map) {
if (map.hasOwnProperty(key)) {
return false;
}
}
return true;
}
check it by jQuery.isEmptyObject()
jQuery.isEmptyObject({}); // true
jQuery.isEmptyObject({ foo: "bar" });
https://api.jquery.com/jQuery.isEmptyObject/
Check the length of your object also the length of your keys.
if (Object.keys(vm.occupantDetail.contactDetail).length > 0)
{
// vm.occupantDetail.contactDetail has values
}

$.grep returning undefined when comparing ID to variable

I have a $.each loop in my code which loops through items in one array and tries to find corresponding items in another array.
One array is a structure array, with all the items I need. The other array contains only the items which have a value associated.
I tried the following code:
$.each(placementStructureHaspItems, function () {
var haspItem = $.grep(placementValuesHaspItems, function (e) {
return e.HASPID === this.HASPID;
})[0];
if (haspItem != undefined) {
this.CommentsPreText = haspItem.CommentsPreText;
}
});
haspItem is ALWAYS undefined, for every object.
I cannot post an image of what I get if I run in a console in chrome, so I will try and format it as best as possible, where the top line is the code entered into chrome and the second line is the result given. :
$.grep($scope.HaspitemsFromPlacement, function (e) { return e.HASPID === this.HASPID; })[0];
Undefined
$.grep($scope.HaspitemsFromPlacement, function (e) { return e.HASPID === 2; })[0];
Object {HASPID: 2, ParentID: 1, NumberingType: 0, Text: null, YesNoID: 0…}
this.HASPID
2
My main question here is why the grep works with a static number, but not a property of an object which evaluates to the same number.
Thanks in advance for any help.

How to find whether the particular array variable is empty or not in JavaScript?

I have an array variable like Array[0], and now I need to check whether that Array[0] contains value or not inside of it. What should I do?
If you have an array and call it eg. list, then you can check if it has some elements in the following manner:
if (list.length){
// has some elements (exactly list.length elements)
} else {
// does not have any elements
}
See the following for details: Documentation on length property of Array objects in JavaScript
if(array[0] !== undefined){
// array[0] is defined.
}
//pass array variable to this function
function isEmpty(array){
if(array.length == 0)
return true;
else
return false;
}
Checks if that array exists and does something if not so.
if(!array[0])
{
//do something
}

JSON key is called "true", unable to reference in JavaScript(JSfiddle example)

First of all, I converted a Plist(XML formatted) to JSON with some online tool, this isn't the problem. I managed to pick the important values from this rather big JSON file. With this important information I am rebuilding a new JSON file that is very lean and contains information I can use for a plug-in — that I will create later.
The plist conversion to JSON is ugly. At some point <true/> and <false/> are converted to JSON, leaving this in the JSON: "false":"", or "true":"",.
I am using jQuery
check JSfiddle for an example jsfiddle example
or here
// Simplified (not really a JSON file, but this will do it for explaining)
var themeJSON = {
"item": {
"false": "",
},
};
// I need to know if its enabled: "true" or disabled: "false"
// function for checking if this is the default option
function checkDefault() {
// true is a keyword!
if (themeJSON.item.true) {
return "1";
// so is false!
} else(themeJSON.item.false) {
return "0";
}
}
Maybe I use some other function such as find() ?
updated for answer:
thanks to the comments, this is what I have now:
function checkDefault() {
if (item.hasOwnProperty("true")) {
return "1";
} else if(item.hasOwnProperty("false")) {
return "0";
}
}
Try using the property name as a string:
if (themeJSON.item['true']) {
return '1';
}
else if (themeJSON.item['false']) {
return "0";
}
edit — a comment correctly points out that though accessing the properties by string value will indeed work, your code is otherwise flawed. If the properties are really being given empty string values, then what you really need is a way to test whether the property is there at all, and not (as this code does) just check the value of the property:
if (typeof themeJSON.item['true'] !== 'undefined') { ... }
or, alternatively:
if ('true' in themeJSON.item) { ... }
An explicit check for equality against the empty string would do too:
if (themeJSON.item['true'] === '') { ... }
When an object property has a name which is a reserved keyword, the array index notation can be used to reference it.
A way of checking whether item has a property named false:
> themeJSON.item.hasOwnProperty("false");
true
This not ideal because a single object could have both a false property and a true property.
In JS, foo.bar is the equivalent of foo['bar']. Therefose:
if (themeJSON.item['true'] === "")
Note the need for === as false == "" but false !== "".
Also, I must nitpick. themeJSON is no longer JSON since it's not a string - it's just another JavaScript object. You shouldn't confuse those two.
Try this code
function checkDefault() {
// true is a keyword!
if ("true" in themeJSON.item) {
return "1";
// so is false!
} else if ("false" in themeJSON.item) {
return "0";
}
}

Categories