How to properly access nested JavaScript objects? - javascript

I have ruby background and am converting some ruby code to JavaScript.
I'm trying to understand the difference between hashes in ruby and JavaScript.
I have a hash in ruby that looks like below:
main_hash = {"query" => { "filtered" => { "query"=> { "bool" => query_hash}}}}
I think the proper conversion for this in JavaScript would be basically a JSON like below:
var main_hash = {"query" : { "filtered" : { "query" : { "bool" : query_hash}}}}
But, I have some ruby logic that I'd like to replicate in JavaScript. And that code is:
if(query_hash.empty?)
main_hash["query"]["filtered"].delete("query")
else
main_hash["query"]["filtered"]["query"]["bool"] = query_hash
end
How do I access the nested attributes in JavaScript?
The reading I've been doing on w3schools indicates the below is the correct conversion, but I want to make sure I'm not missing any language semantics in this conversion. For example the delete only deletes the query object contained in filtered which is contained in query that is contained in main_hash correct?
if(!isEmptyObject(query_hash)){
delete main_hash.query.filtered.query;
} else {
main_hash.query.filtered.query.bool = query_hash;
}

In JavaScript, your Ruby hash equivalent is an object. Properties of objects can be accessed two ways.
You can access them with the dot notation:
main_hash.query.filtered.query
Or using the array like access:
main_hash["query"]["filtered"]["query"]
Both work. And yes, the delete would only delete the innermost query property.

If you are using JQuery your code is ok, but if you are not, you need to create this isEmptyObject function.
You can use something like this function
function isEmpty(obj) {
// Speed up calls to hasOwnProperty
var hasOwnProperty = Object.prototype.hasOwnProperty;
// null and undefined are "empty"
if (obj == null) return true;
// Assume if it has a length property with a non-zero value
// that that property is correct.
if (obj.length > 0) return false;
if (obj.length === 0) return true;
// Otherwise, does it have any properties of its own?
// Note that this doesn't handle
// toString and valueOf enumeration bugs in IE < 9
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) return false;
}
return true;
}
Examples:
isEmpty(""), // true
isEmpty([]), // true
isEmpty({}), // true
isEmpty({length: 0, custom_property: []}), // true
isEmpty("Hello"), // false
isEmpty([1,2,3]), // false
isEmpty({test: 1}), // false
isEmpty({length: 3, custom_property: [1,2,3]}) // false

Related

How to replace a dynamically specified attribute in JS object

The attribute(or the nested object) is selected dynamically based on conditions. It can be one of the 4 possibilities as follows:
var tempData = o.title ? o["properties"] || o["items"]["properties"] : o[k]["properties"] || o[k]["items"]["properties"];
Then I get this new data, I want to replace the above selected with.
var newData = //some new Object
I want to replace whatever above selected with the new data. I could do the following (go through the condition again and set the new data):
if(o.title){
if (o["properties"]) {
o["properties"] = newData;
} else if (o["items"]["properties"]) {
o["items"]["properties"] = newData;
}
}else{
if (o[k]["properties"]) {
o[k]["properties"] = newData;
} else if (o[k]["items"]["properties"]) {
o[k]["items"]["properties"] = newData;
}
}
But it doesn't look good. What is the more sophisticated way of achieving this?
It is unclear if you are generically attempting to replace any properties property with the newData, or if you are wanting it to specifically be one of the ones you have specified in your code. I have assumed that you are only wanting to replace the ones you specifically have shown in your code.
Note: The following assumes that it is not possible for the value of the properties property to evaluate to false. If it is possible for it to have a value that evaluates to false, this will fail.
As a first pass, I would do something like:
var p;
if (o.title) {
p=o;
} else {
p=o[k];
}
if (p.properties) {
p.properties = newData;
} else if (p.items.properties) {
p.items.properties = newData;
}
However, that relies on:
o is not null or undefined.
o.title does not evaluate to false, if you are trying to test for the existence of o.title.
k is valid/defined.
p (i.e. o[k]) is not null or undefined (i.e. is an Object)
p.properties does not evaluate to false, if you are testing for existence
p.items is not null or undefined (i.e. is an Object)
p.items.properties does not evaluate to false, if you are testing for existence
A more robust implementation would be:
if (typeof o === 'object' && o !== null) {
var p;
if (o.hasOwnProperty('title')) {
p = o;
} else {
p = o[k];
}
if (typeof p === 'object' && p !== null) {
if (p.hasOwnProperty('properties')) {
p.properties = newData;
} else if (typeof p.items === 'object' && p.items !== null
&& p.items.hasOwnProperty('properties')) {
p.items.properties = newData;
}
}
}
This still relies on:
k is valid/defined.
Basically, it is OK to use shortcuts like if(o.title) to test for existence, if you know that
the possible values for o can not include ones which might make your code throw an error (e.g o is null or undefined), and
the possible values for o.title do not evaluate to false when the property actually exists (e.g. o.title is null, undefined (yes, the property can exist, but have the value undefined), false, 0, '', etc.).
If you are going to perform the replacements in other areas of your code, or if you are going to use property keys other than hard coded items, and properties, then you should create a function. Assuming you are only performing this replacement in this section of your code, using a variable to hold the object in which you are looking for properties is faster/more efficient than creating a function.
Ok, from what i can understand here, it's like you are trying to replace the "properties" with the new data, and you want this to be able to be done dynamically, or maybe i can say, you need to do this regardless the structure.
lets see, if your objective is anything that end up with "properties", lets do it like this:
function recReplace(current,target,replacement){
for (var i in current){
if (i == target){
current[i] = replacement;
}
else{
recReplace(current[i],target,replacement);
}
}
}
And in the end you call
recReplace(o,"properties",newData);
But this will replace whole "properties" key with newData in DFS way, you can do additional conditional if you want to replace it only the first occurence

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
}

Where can I see the source code for JavaScript methods, such as hasOwnProperty, in Node.js?

I have been studying JavaScript algorithms and Big O for interviews. I was told that knowing the runtimes of built-in methods, such as Object.prototype.hasOwnProperty and Array.prototype.map, is important.
What is a simple way to view the source code for these functions in node.js? I have a local copy of node.js, and I tried to search for these methods in my text editor, but it's not as straightforward as I thought.
Object.prototype.hasOwnProperty()
From a Javascript interview point of view, I would think you just need to fully understand what obj.hasOwnProperty() does at the Javascript level, not how it's implemented inside of V8.
To do that, you should fully understand this little snippet:
function MyConstructor() {
this.methodB = function() {}
}
MyConstructor.prototype = {
methodA: function() {}
};
var o = new MyConstructor();
log(o.hasOwnProperty("methodA")); // false
log(o.hasOwnProperty("methodB")); // true
o.methodA = function() {}; // assign "own" property, overrides prototype
log(o.hasOwnProperty("methodA")); // true
This is because .hasOwnProperty() looks only on the object itself and not on the prototype chain. So properties which are only on the prototype chain or do not exist at all will return false and properties which are directly on the object will return true.
Array.prototype.map()
A polyfill in Javascript for Array.prototype.map() is here on MDN which will show you exactly how it works. You can, of course, do the same type of search I did above in the Github repository to find the .map() implementation too if you want.
Array.prototype.map() is pretty simple really. Iterate over an array, calling a function for each item in the array. Each return value of that function will be used to construct a new array that will be returned from the call to .map(). So, conceptually, it's used to "map" one array to another by calling some transform function on each element of the original array.
In the simplest incarnation, you add 1 to each element of an array:
var origArray = [1,2,3];
var newArray = origArray.map(function(item, index, array) {
return item + 1;
});
console.log(newArray); // [2,3,4]
Actual V8 source code:
If you really want to see how it is implemented inside of V8, here are code snippets and links to the relevant actual code files. As you can see, most of it is in C++ and to understand it, you have to understand how objects are structured in memory and what C++ methods they have internally in V8. This is very V8-specific, not general Javascript knowledge.
I've included links to the relevant source files too so if you want to see other context in those files, you can click on the links to see that.
In v8.h:
V8_DEPRECATED("Use maybe version", bool HasOwnProperty(Local<String> key));
V8_WARN_UNUSED_RESULT Maybe<bool> HasOwnProperty(Local<Context> context, Local<Name> key);
In api.cc:
Maybe<bool> v8::Object::HasOwnProperty(Local<Context> context,
Local<Name> key) {
PREPARE_FOR_EXECUTION_PRIMITIVE(context, "v8::Object::HasOwnProperty()",
bool);
auto self = Utils::OpenHandle(this);
auto key_val = Utils::OpenHandle(*key);
auto result = i::JSReceiver::HasOwnProperty(self, key_val);
has_pending_exception = result.IsNothing();
RETURN_ON_FAILED_EXECUTION_PRIMITIVE(bool);
return result;
}
bool v8::Object::HasOwnProperty(Local<String> key) {
auto context = ContextFromHeapObject(Utils::OpenHandle(this));
return HasOwnProperty(context, key).FromMaybe(false);
}
In v8natives.js:
// ES6 7.3.11
function ObjectHasOwnProperty(value) {
var name = TO_NAME(value);
var object = TO_OBJECT(this);
return %HasOwnProperty(object, name);
}
In objects-inl.h:
Maybe<bool> JSReceiver::HasOwnProperty(Handle<JSReceiver> object,
Handle<Name> name) {
if (object->IsJSObject()) { // Shortcut
LookupIterator it = LookupIterator::PropertyOrElement(
object->GetIsolate(), object, name, LookupIterator::HIDDEN);
return HasProperty(&it);
}
Maybe<PropertyAttributes> attributes =
JSReceiver::GetOwnPropertyAttributes(object, name);
MAYBE_RETURN(attributes, Nothing<bool>());
return Just(attributes.FromJust() != ABSENT);
}
In runtime-object.cc:
static Object* HasOwnPropertyImplementation(Isolate* isolate,
Handle<JSObject> object,
Handle<Name> key) {
Maybe<bool> maybe = JSReceiver::HasOwnProperty(object, key);
if (!maybe.IsJust()) return isolate->heap()->exception();
if (maybe.FromJust()) return isolate->heap()->true_value();
// Handle hidden prototypes. If there's a hidden prototype above this thing
// then we have to check it for properties, because they are supposed to
// look like they are on this object.
if (object->map()->has_hidden_prototype()) {
PrototypeIterator iter(isolate, object);
DCHECK(!iter.IsAtEnd());
// TODO(verwaest): The recursion is not necessary for keys that are array
// indices. Removing this.
// Casting to JSObject is fine because JSProxies are never used as
// hidden prototypes.
return HasOwnPropertyImplementation(
isolate, PrototypeIterator::GetCurrent<JSObject>(iter), key);
}
RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate);
return isolate->heap()->false_value();
}
RUNTIME_FUNCTION(Runtime_HasOwnProperty) {
HandleScope scope(isolate);
DCHECK(args.length() == 2);
CONVERT_ARG_HANDLE_CHECKED(Object, object, 0)
CONVERT_ARG_HANDLE_CHECKED(Name, key, 1);
uint32_t index;
const bool key_is_array_index = key->AsArrayIndex(&index);
// Only JS objects can have properties.
if (object->IsJSObject()) {
Handle<JSObject> js_obj = Handle<JSObject>::cast(object);
// Fast case: either the key is a real named property or it is not
// an array index and there are no interceptors or hidden
// prototypes.
// TODO(jkummerow): Make JSReceiver::HasOwnProperty fast enough to
// handle all cases directly (without this custom fast path).
Maybe<bool> maybe = Nothing<bool>();
if (key_is_array_index) {
LookupIterator it(js_obj->GetIsolate(), js_obj, index,
LookupIterator::HIDDEN);
maybe = JSReceiver::HasProperty(&it);
} else {
maybe = JSObject::HasRealNamedProperty(js_obj, key);
}
if (!maybe.IsJust()) return isolate->heap()->exception();
DCHECK(!isolate->has_pending_exception());
if (maybe.FromJust()) {
return isolate->heap()->true_value();
}
Map* map = js_obj->map();
if (!key_is_array_index && !map->has_named_interceptor() &&
!map->has_hidden_prototype()) {
return isolate->heap()->false_value();
}
// Slow case.
return HasOwnPropertyImplementation(isolate, Handle<JSObject>(js_obj),
Handle<Name>(key));
} else if (object->IsString() && key_is_array_index) {
// Well, there is one exception: Handle [] on strings.
Handle<String> string = Handle<String>::cast(object);
if (index < static_cast<uint32_t>(string->length())) {
return isolate->heap()->true_value();
}
} else if (object->IsJSProxy()) {
Maybe<bool> result =
JSReceiver::HasOwnProperty(Handle<JSProxy>::cast(object), key);
if (!result.IsJust()) return isolate->heap()->exception();
return isolate->heap()->ToBoolean(result.FromJust());
}
return isolate->heap()->false_value();
}
This is the node.js Github repository. If you know what to search for and have enough patience to wade through all the search hits, you can generally find anything you need. The unfortunate thing about searching on Github is I have not found any way to remove all the test sub-directories from the search so you end up with 95% of the search hits in the test code, not in the actual implementation code. But, with enough persistence, you can eventually find what you need.

For...in loop filtering only objects

Is there a way to filter out everything inside of a for...in loop to only get the objects?
I'm writing a function to loop through nested objects to find certain pieces of data and then save it to localStorage.
Example:
var equipped = {
data: [the rest of the properties of equipped go here],
tool: {
data: [the rest of the properties of tool go here],
axe: {
data: [the rest of the properties of axe go here],
iron: {...},
steel: {...}
}
}
}
The tool/axe/metal properties are all generated dynamically and is different each time. Inside the metal properties is the data I'm trying to save. I would normally just loop through the array if I was trying to access the data (Using knockoutjs for binding, it's much easier to just foreach the data array), but I'm using the variable from a for...in loop to build the rest of the tree in my localStorage object before stringifying it.
How I'm reading the object:
for (var type in equipped) {
if (check goes here) {
savedValue.equipped[type] = {};
for (var category in equipped[type]) {
etc etc...
}
}
}
I understand that everything is an object type so I can't just do an instanceof or typeof on a defined object to filter them out. Is there another easy way to do it inside of an if statement or do I have to make each step of the tree from a constructor so I can instanceof RealObject?
Either of these should do well:
function isObject(val) {
if (val === null) { return false;}
return (typeof val === 'object');
}
or
function isObject(obj) {
return obj === Object(obj);
}
or
// this only works with object literals
function isObject(val) {
return (!!val) && (val.constructor === Object);
};
this last one, gives me the following:
console.log(isObject()); // false
console.log(isObject([])); // false
console.log(isObject(new Date)); // false
console.log(isObject({})); // true
console.log(isObject(null)); // false
console.log(isObject(true)); // false
console.log(isObject(1)); // false
console.log(isObject('someValueString')); // false
so, something like:
for (var type in equipped) {
if (isObject(type)) {
savedValue.equipped[type] = {};
for (var category in equipped[type]) {
etc etc...
}
}
}
Note: You can also try the following, but I have not used it. So you'd have to go thru your use cases.
Object.getPrototypeOf
Here is the code to check whether the variable is object or not:
function isJsonObject( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || obj.toString() !== "[object Object]" || obj.nodeType || obj.setInterval ) {
return false;
}
// Not own constructor property must be Object
if ( obj.constructor
&& !obj.hasOwnProperty("constructor")
&& !obj.constructor.prototype.hasOwnProperty("isPrototypeOf")) {
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || obj.hasOwnProperty( key );
}
There's an old hack for type detection I've used previously.
var classChecker = {}.toString;
classChecker.call({});
classChecker.call(function() {});
classChecker.call([]);
// etc...
// More immediately relevant use:
var savedValue = {
equipped: {}
};
var objectString = classChecker.call({});
for (var type in equipped) {
if (classChecker.call(equipped[type]) === objectString) {
savedValue.equipped[type] = {};
for (var category in equipped[type]) {
// ...
}
}
}
console.log(savedValue);
See http://plnkr.co/edit/nKLQsOdcurrpUCg7cOoJ?p=preview for a working sample. (open your console to view output)

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