What is the most efficient way to create multiple nested property objects in a shorter amount of time?

Currently, I am utilizing mongoDB for a data migration project where queries are written in plain JavaScript/JSON format:

queryObj = {}; // main object passed to mongodb for queries

The code snippet below is causing an error:

queryObj[inObj.row]['$eq'] = inObj.equals;

However, the following code snippet works without any issues:

queryObj[inObj.row[i]] = {};
queryObj[inObj.row]['$eq'] = inObj.equals;

Is there an easier way to create objects with multiple nested properties without explicitly defining each one as an object? Perhaps using Object.create or another built-in solution?

Answer №1

If you need to ensure that certain objects exist, one approach is to create a method that generates empty objects when necessary.

/**
 * To establish a deep property on an object, generate any mandatory
 * objects within the hierarchy that may not presently exist
 * @param {object} obj The target object for properties
 * @param {string} prop Dot-separated deep property to assign
 * @param {*} value Value to assign to the property
 */
function setProp(obj, prop, value) {
  var parts = prop.split('.');
  var i = 0;

  for (; i < parts.length - 1; i++) {
    if (typeof obj[parts[i]] === 'undefined') {
      obj[parts[i]] = {};
    }
    obj = obj[parts[i]];
  }
  // Keep in mind that parts[i] points to the last part of the deep property name
  // and obj refers to the nested object containing the last deep property
  obj[parts[i]] = value;
}

   
var obj = {}
setProp(obj, 'a.b.c', 3);

console.log(obj.a.b.c); // 3

In your scenario, you could do something like this:

setProp( queryObj, inObj.row + ".$eq", inObj.equals );

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

What methods can be used to create a universal JS function for popup windows?

How can I create a more flexible code structure? I have successfully implemented the functionality using the following approach: let popup1 = document.getElementById("popup-1"); function openPopup1() { popup1.classList.add("open-popup& ...

Transforming PHP shortcode into JQuery functionality

My website is built on Wordpress, and I use javascript to load some of the content. Here's an example: jQuery(".portfolio-fs-slides").css({"display":"none"}).prepend('<div class="portfolio-fs-slide current-slide portfolio-ppreview"><d ...

Download multiple Highcharts graphs on a single page

When using Highchart Export, I am currently able to download multiple graphs in a single page PDF. However, I would like the first graph to be on the first page and the second graph on the second page when saving as a PDF. You can find the code in the fol ...

The date comparison feature in MongoDB is failing to function properly with the $lt operator

As I work with the MongoDB aggregation pipeline, I am facing an issue where I need to compare a date with the current date but with the time set as "T00:00:00.000+00:00". Despite setting up the operation correctly, the $lt operator is not returning any d ...

Activate the text area message by clicking on the href link

I am currently working on customizing the intercom plugin for a WordPress site. My goal is to have a message triggered when a user clicks on a hyperlink, essentially simulating the enter key press in a textarea. Here is the code snippet that I am using: ...

What is the most effective method for retrieving Key-Value Pairs from a disorganized String?

Avoiding hard-coded rules specific to certain patterns is crucial. I am currently working on a project similar to AWS Textract (link here). I have successfully extracted data from files, albeit in an unstructured manner. Now, my goal is to find the best w ...

Using specific delimiters in Vue.js components when integrating with Django and Vue-loader

While working on my Django + Vue.js v3 app, I came across a helpful tool called vue3-sfc-loader. This allows me to easily render .vue files using Django, giving me the best of both worlds. The current setup allows Django to successfully render the .vue fil ...

Facing an obstacle in Angular as I am unable to view my data

How can I bind the model of my controller in the init function and see the data when the init is called? Index.html <!DOCTYPE html> <html ng-app="I-Sign"> <head> <meta http-equiv='X-UA-Compatible' content='IE=edge&apo ...

How can we display or conceal text indicating the age of a patient based on the value returned from selectedPatient.age in a React application?

Hello, I am looking to dynamically display the age in years on the screen based on the value retrieved from selectedPatient.age, toggling between visible and hidden states. import React, { useContext } from 'react'; import { useHistory } from &ap ...

Angularjs drop-down menu changes images with animation

<body ng-controller="myCtrl"> <input type="checkbox" ng-model="loaded"/> <select ng-model="list"> <option ng-repeat="option in data.availableOptions" value="{{option.name}}">{{option.id}}</option> </select> {{list}} &l ...

What is the process for inserting text within a .data() method?

I have set up this AJAX request: $.ajax({ method: "GET", url: $('.item').data('query_selector'), dataType: "html" (The ajax call works perfectly, returning something like "item=Mann+Co.+Supply+Crate&quality=6&trad ...

The Best Way to Filter Mongo Documents Using Nested Objects

Is there a way to locate a room by its ID and confirm that it includes the current player? Within my mongodb database, I have a collection of rooms that contain players who are users. const RoomSchema = new Schema({ players: [{ type: Schema.Types.Objec ...

The Naming Convention for NPM Scripts

In my package.json, I have a script that looks similar to this: { ... scripts: { ... "testdb:e2e": "TESTDB_ENV='...' gulp mocha:e2e:backend && gulp mocha:e2e:frontend" } ... } I am interested in adding a s ...

Tips for integrating Redux toolkit with the latest version of Next.js

It seems that in order to incorporate redux into my app, I must enclose the majority of it within a redux provider, which should be a client component. As a result, almost every part of my app becomes a child of this client component. Does this imply tha ...

Implement a logging system to track and record data from both incoming requests and outgoing responses on a server powered by Express and Node.js

Is there a way for my server to log the response and request data when posting to another server? Thank you. const request = require('request'); postToIotPlatform = function postToIotPlatform(req, res, next) { var formData = JSON.stringify( ...

Utilize MaterialUI's stepper component to jazz up your design with

Is there a way to customize the color of a material ui Stepper? By default, the material UI stepper's icons use the primary color for both "active" and "completed" steps. class HorizontalLinearStepper extends React.Component { state = { activeS ...

Facing an issue where WordPress AJAX is not showing the expected content

Currently, I am in the process of creating a WordPress website that will feature an initial display of two rows of images. Upon clicking a button, two more rows should dynamically appear. There are four key files involved in this project: case-study-ca ...

Storing Redux state in local storage for persistence within a React application

Recently, I've been experimenting with persisting data to local storage using Redux. My approach involved creating an array of alphabet letters and setting up an event listener to log a random letter each time it's clicked. However, despite succe ...

What methods can be used to monitor changes made to thumbnails on the YouTube platform?

I have embarked on a project to create a Chrome extension that alters the information displayed on the thumbnails of YouTube's recommended videos. In this case, I am looking to replace the video length with the name of the channel. Imagine you are on ...

Using jQuery to Check Cookies and Hide Content Depending on the Value and Data Attributes

On a webpage, I have a collection of coupons with unique data attributes (data-coupon). Currently, I am using cookies to store the value associated with each coupon (ranging from 1 to 4). While my code is functional, it feels repetitive and cumbersome. S ...