Manipulating properties within Javascript objects is a common task in web development. By

Just diving into the world of javascript and have a question to ask (obviously :P). I've developed two methods - one fetches value from an object based on its data path (structure within an object like "object.subObject.anotherSubObject.property"), and another sets a value to an object using the data path.

Check out the TypeScript code snippet below:

public getValueFromObject(object:any, path:string|string[], thisArg:any = null):any {
    // code for fetching value from object...
}

private setValueToObject(dataObject:any, value:any, dataPath:string|string[], thisArg:any = null):any {
    // code for setting value to object...
}

My query is about the quality of this JavaScript code. Are there any libraries, like lodash, that could simplify what I'm attempting to achieve? It would be great if someone could provide an example code. Thank you in advance!

Answer №1

Manipulating objects in JavaScript is quite flexible.

Create a new object

var myobj = {
    var1: 'hello'
}

Retrieve var1

console.log(myobj.var1) // 'hello'

Update var1

myobj.var1 = 'world'

Retrieve var1 once more

console.log(myobj.var1) // 'world'

Combine everything to display 'hello world' on your console

var myobj = { var1: 'hello' };
console.log(myobj.var1);
myobj.var1 = 'world';
console.log(myobj.var1);

Aside from that, your code appears solid. Remember, there are multiple approaches to achieve the same result in programming, and it's good practice to experiment with different methods. While coding for fun, it's beneficial to also learn efficient techniques for optimizing your code in production environments.

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

Django: The Art of Rejuvenating Pages

Consider the following code snippet which updates the timestamp of a database model whenever it is accessed: def update_timestamp(request): entry = Entry.objects.filter(user=request.user) entry.update(timestamp=timezone.now()) return HttpRespo ...

JQuery's worldwide network of AJAX handlers

Utilizing global AJAX handlers such as $(document).ajaxError(function(e, xhr, settings, exception) { }); $(document).ajaxStart(function(e, xhr, settings, exception) { $(".spinner").show(); }) $(document).ajaxComplete(function(e, xhr, settings, exce ...

Guide to resetting an input form upon submission in ReactJS

I'm encountering some challenges in resetting my input form upon submission. My goal is to have the input field clear out its value after a successful form submission, but for now, I'd settle for it simply resetting on submit in general. Unfortun ...

Encountering an unexpected token error while using Webpack with React modules

I've been attempting to utilize the react-spin npm package, but when I try to create a bundle.js with webpack, an error occurs: Module parse failed: /Users/nir/browsewidget/node_modules/react-spin/src/main.js Line 29: Unexpected token < You may ne ...

Understanding Typings in Typescript

Just delving into the world of Angular2 and finding it quite exciting, but running into a roadblock with Typings. The concept is not clear to me - how do I utilize them and what purpose do they serve? Different sources suggest different approaches, some me ...

Feature for inserting and displaying a new item within an array

Recently, I started experimenting with AngularJS and I have a project in mind. I want to create an app where users can add another person's name and date of birth. Currently, I have initial data for 2 people and their dates of birth. I envision users ...

Having trouble setting up mongodb-memory-server 8 to work with jest

I am currently working on integrating the latest version of mongodb-memory-server with jest on a node express server. While following the guide provided in the mongodb-memory-server documentation (), I encountered some gaps that I am struggling to fill in. ...

Issues persist with Webpack 4's UglifyJS failing to minify and compress code

My current setup involves webpack 4 and React, and I'm uncertain about whether my code is being compressed and minified properly. The issue arises when using the UglifyJS plugin in webpack's plugin property or the optimization property. When util ...

Error: Invariant Violation - The text string must be enclosed within a <Text> component

Hey there, I hope you're doing well! So, I've been diving into the world of React-Native to build a weather app. Everything was going smoothly until I encountered this pesky error: Text strings must be rendered within a <Text> component. - ...

When the objects in the v-for loop are modified, the rerender does not occur to update the changes in

My issue involves using mounted(), along with reloadComparisons(), and this specific tag: <li v-for="comparison in comparisons">C: [[ comparison.area ]]</li> The problem arises when the rendering only occurs if comparisons is defined within d ...

Emberjs: Developing a self-focusing button with Views/Handlebar Helpers

Currently, I am using a Handlebars helper view that utilizes Em.Button (although it's deprecated) to create a Deactivate Button. This button is designed to focus on itself when it appears and clicking it triggers the 'delete' action. Additio ...

Looking to transform a timestamp such as "2021-07-18T9:33:58.000Z" into a more readable format like 18th July for the date or 9:33 am for the time using Angular?

Is there a way to convert the Timestamp format "2021-07-18T9:33:58.000Z" to display as 18th July (for date) or 9:33 am (for time) in an Angular 11 application? Currently, my code looks like this: const myDate = new DatePipe('en-US').transform ...

Ways to dynamically update button properties in Angular 2

Customized Template, <div *ngFor="let item of items" class = "col-sm-12 nopadding"> <a class="button buttonaquacss button-mini button-aqua text-right pull-right" [ngClass]="{activec: isActive}" (click)='updateStatus(item)& ...

developing a star rating system for a mobile website

Can star ratings be implemented in a mobile website using HTML, CSS, and JS? The HTML code for the stars is as follows: <div class="rating"> <span>☆</span><span>☆</span><span>☆</span><span>☆</sp ...

Issue with Javascript and Ajax function not resolving

I'm currently working on a feature that updates my database when a user clicks a specific link. Each link has a different value - for example, one increases by 1, another by 2, and so forth. My goal is to submit a form to a separate page with the dat ...

PHP array does not retain a variable

While building a website, I encountered a perplexing bug during coding. The issue arises when I store MySQL query results in an array and then call a JavaScript function with that data. Initially, the array contains 9 items: 8 of type tinyint(4) (from the ...

Creating fixed table headers can be achieved using the pivottable.js library

Seeking help with implementing a fixed table header on my Django site using the JavaScript plugin pivottable.js. The goal is to have the header stay at the top of the div while scrolling down to display large datasets. However, since the tables are created ...

Incorporating data from an api call to establish the starting state of a react component

I have been delving into the world of React and TypeScript while working on a fun project - a word guessing game inspired by Hangman. In this game, players have 5 chances to guess the correct word, which is retrieved from an API call. I populate an array w ...

Error occurs when attempting to filter data through input text pasting in Angular

Currently, I am working on a web application that utilizes the Angular framework and angularfire2. The issue I am encountering is related to the data filter functionality not functioning correctly when pasting copied text. Interestingly, it works perfectly ...

Observable function encountering difficulties returning nested values

I've been working on a function that returns an observable. test(id: int): Observable<Group>{ this.http.get('test/').subscribe( (result:any) => { resultingVal = Group.fromJson(result.group); }); } Right now, the function ...