Struggling to retrieve a property value from an object in JavaScript

I am having trouble reading an Object property that I retrieved with MongoDB while working with MeteorJS. The object creation process is as follows:

header = ["name"];
values = ["word1", "word2"];
var tmp = {};
var data = new Array();
for (var cnt = 0; cnt < values.length; cnt++){
    for (var i = 0; i < header.length; i++) {
         temp[header[i]] = values[i];
    }
data.push(temp);

After creating the object, I insert it into MongoDB using the following code:

for (obj in data) {
    Badwords.insert(data[obj]);
}

However, when I try to access and read the property, the browser console shows inconsistencies:

Badwords.findOne()

Object {_id: "uNRNDtp3RGrKA6gWz", "name": "word1"}

Badwords.findOne().hasOwnProperty("name")

false

Badwords.findOne().hasOwnProperty('name')

false

Badwords.findOne().hasOwnProperty('\"name\"')

false

Badwords.findOne().hasOwnProperty('\'name\'')

false

Badwords.findOne().hasOwnProperty("\'name\'")

false

Badwords.findOne().hasOwnProperty("\"name\"")

false

Badwords.findOne()

Object {_id: "uNRNDtp3RGrKA6gWz", "name": "word1"}

Badwords.findOne()["name"]

undefined

On the other hand, when checking for "_id" property:

Badwords.findOne().hasOwnProperty("_id")
true

The issue may lie in the property name itself: "name" instead of name. Also, the keys are undefined.

Badwords.findOne().keys
undefined

To address this, I created a method called getKey():

var myObj = Badwords.findOne()
undefined

myObj.getkey = function(obj){
   var keys = [];
   for(var key in obj){
      keys.push(key);
   }
   return keys;
}
myObj.getkey(myObj)
["_id", "name", "getkey"]

Answer №1

After testing your code, I identified 2 bugs. Firstly, there was a missing } at the end of the first for loop. Secondly, you defined a tmp object but used temp instead. The corrected code I ran is as follows:

header = ["name"];
values = ["word1", "word2"];
var temp = {};
var data = new Array();
for (var cnt = 0; cnt < values.length; cnt++) {
  for (var i = 0; i < header.length; i++) {
    temp[header[i]] = values[i];
  }
  data.push(temp);
}
for (obj in data) {
  Badwords.insert(data[obj]);
}

Subsequently, using hasOwnProperty will produce the desired results:

Badwords.findOne().hasOwnProperty("name");
true

Answer №2

The attribute name is set to "name" and consists of 5 characters. To verify this:

let property = '';
for (let index in Badwords.findOne()) {
    property = index;
}
"name"

property.length
5

property.charCodeAt(0)
65279

property.charCodeAt(1)
110

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Hover effect for changing image source not functioning as anticipated

I'm having issues creating an image that plays a GIF on hover. I came across some jQuery code on this website that should work, but it's not working for me. Any thoughts on what the problem might be? Here is the HTML and JavaScript code: $(doc ...

Resetting JavaScript Input based on certain conditions

I have been attempting to reset the input fields for a login when the loginDiv display is set to none, but unfortunately it does not seem to be working as expected. My goal is for the input fields to reset whenever the login button is clicked and the logi ...

`How can I use lodash to filter an array based on any matching value?`

I have a collection of objects and I need to search for instances where certain properties match specific values. Here is an example array: let arr = [ { a: 'foo', b: 'bar' }, { a: 'bar', ...

Instructions on how to dynamically update a form field based on the input in another field using conditional statements

I'm seeking advice on how to automatically update a field based on user input without the need for manual saving. For example, if the user types '95' in the input field, the equivalent value displayed should be '1.0' in real-time. ...

Searching for a specific value in various Json files: A guide

My goal is to create an application where users can input longitude and latitude coordinates of a location, and the application will return the associated grid code from one of three JSON data files. I am attempting to search through all three files simult ...

Is there a way to create a function that is able to return both a value and a promise

Assume I need to fetch a value only if an object is already present in my model. Otherwise, I should retrieve the output of an endpoint service: model.getDoohkyById = function( id ){ if( this.data ) { if( this.data.length > 0) { ...

Step-by-step guide on implementing a border-bottom for an active link

Is there a way to apply a border-bottom to btn_articles and btn_posts when one of them is clicked? I attempted to use the active class but it did not have the desired effect. Any suggestions or solutions would be greatly appreciated. let btn_articles = ...

What are the essential Bootstrap CSS and JavaScript files that need to be connected to our HTML document?

I recently downloaded the most recent version of Bootstrap, which is version 4. Upon extraction, I noticed that it includes two folders: one for CSS and the other for JS. The CSS folder consists of approximately 12 CSS files, while the JS folder contains ...

The modifications made to the input type="time" in View do not get updated in the Model within Angular

I have been attempting to validate the input type "time", but I am encountering an issue where changes in the view are not reflected in the model if any of the input fields are left empty. For example: https://i.sstatic.net/1U0sO.png When a user change ...

The length property of a jQuery array may not always match the actual length of the array

Recently delving into jquery, I encountered the issue described in the title. Below is an excerpt from my controller code: [HttpPost] public JsonResult getProjectList() { List<Project> projectList = new List<Project>(); ...

What is the best way to include a class in the <td> element of a dynamic table?

My goal is to sum up the values in a specific column of a dynamic table by attaching an id property to each row. I am specifically focused on assigning an id to each <td> in every row of the table. UPDATE: Although I have all 4 keys in the <td> ...

Delay in only a portion of the AJAX response

I created a chat application that is functioning correctly, but I am encountering an unexpected behavior. When a user sends a message, the user's name, time, and message should be displayed in order. However, currently, it seems like the username and ...

Is a Toolbar plugin or custom Toolbar options the better choice for your project?

Could anyone recommend a Jquery plugin for adding a ToolBar option to my web application? I've searched and researched for the past 48 hours but haven't found a reliable one yet. If the recommended toolbar resembles the image below, that would b ...

Using codeigniter and JQuery, I have developed a unique Javascript function to selectively extract a specific portion of text

I'm currently working with the following syntax: $("#orderbynumber").autocomplete( { source: "get_orders_by_order_number", messages: { noResults: '', results: function() {} }, select: function( event, ui ) { var select ...

Sort data in MongoDB based on the highest number of occurrences

Looking to organize a collection by the highest number of occurrences for any value. For example: { "id": "ID", "fruit": 'Apple' }, { "id": "ID", "fruit": 'Banana' }, ...

Implementing custom _id generation, sorting by _id, and inserting rows between existing rows in a React Data Grid by altering the default natural order of MongoDB

I am currently developing a web application similar to Excel, and I am looking to add a feature that allows users to insert rows freely. While I can easily adjust the frontend to show where the insertion should happen using splice and the selected row ID, ...

What could be the reason my hex code generator is outputting variable names instead of their assigned values?

I am currently working on developing a unique hex code generator using random values. At the moment, my focus is on displaying six random values in the HTML. // The characters A-F and numbers 0-9 can be utilized var button = document.querySelector(&quo ...

What is the measure of randomness created by Math.random?

I am trying to create a large random number without the need for cryptographic security. Therefore, I have opted not to use crypto.getRandomValues. Currently, my method of generating the random number is as follows: const random = length => Math. ...

Is it possible for Angular to perform bidirectional data binding in reverse between two input fields?

I'm struggling to get my two input fields to update values when the opposite input is changed. My goal is to create a simple $dollar to Gold oz calculator with two input fields. You can see a sample preview here: http://embed.plnkr.co/dw6xL95zRqJC1p ...

Determine which points fall within a specified radius by utilizing solely an array

I'm developing an application that utilizes Leaflet to store GPS coordinates of specific locations in a table format [lat,lng]. This functionality is only accessible from the back end. On the front end, I need to retrieve the current position and gen ...