change nested object value with a user specified path [duplicate] - javascript

This question already has answers here:
Accessing or creating nested JavaScript objects with string key without eval
(2 answers)
How to set object property (of object property of..) given its string name in JavaScript?
(16 answers)
Closed 3 years ago.
Problem
I want to build a function that takes in a path to a nested object value and sets that value to 'new value'
const obj = {
foo: {
bar: 'baz'
}
}
// api should look like
changeObjKey(o => o.foo.bar)
//or
changeObjKey('foo.bar')
/*
* expected:
obj = {
foo: {
bar: 'new value'
}
}
*/
What I've tried:
Something like this (which obviously doesn't work)
function changeObjKey(cb){
cb(obj) = 'new value'
}
I don't want to use lodash or the likes, I'm looking for the most minimal solution to this problem. I also don't want to use eval and the api should support both foo.bar and foo[bar] (if its string based)

Related

How to access a particular path/adress inside an object? [duplicate]

This question already has answers here:
access object through dot-syntax string path
(2 answers)
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 2 years ago.
I am having a problem which I think I might have figured out before how to do it but I can't remember now and can't figure it out.
Let's say we have an object thats a few levels deep, meaning it has as values other objects which also have as some of the values objects and so on.
Now how could I make a function to which I pass the object and and adress inside it and I can access the value at that location inside the function like this:
const getValueAtAdress = (object, 'country.city.rules') => {
return //here I need to return the value at object.country.city.rules.
}
Am I missing something obvious?
I thought I'd mention here for posterity that what helped me was the answer using the reduce which is exactly what I used before but I could not remember:
Example that I am using for my particular problem:
let stateLocation = address.split('.').reduce((acc, cur) => acc[cur], state);
Your code shows a function declaration but you can't declare an argument name in quotes
You can however call a function and pass a string.
In that case, you just need to split the string into an array and then loop over that array, building up a "chained" set of string indexes that can be passed to the object. The String.split() and Array.reduce() methods are the key.
let obj = {
county: {
city: {
rules: "Strict"
}
}
};
const getValueAtAddress = (object, countyCityRules) => {
// Split the string at the dots to form an array...
// The loop over that array and reduce it with an
// accumulator that is then applied to the object.
return countyCityRules.split(".").reduce((acc, cur) => acc[cur], obj);;
}
console.log(getValueAtAddress(obj, "county"));
console.log(getValueAtAddress(obj, "county.city"));
console.log(getValueAtAddress(obj, "county.city.rules"));

How to destructure an object that contains key names with hyphen? [duplicate]

This question already has answers here:
How to destructure object properties with key names that are invalid variable names?
(3 answers)
Closed 2 years ago.
I'm trying to destructure this object:
{
name: "Bryan",
last-name: "Enid"
}
and this is not possible:
const {name, last-name} = req.body
Is there a way to destructure this, without changing the initial object key name?
You need to rename the variable, because minus is an operator and not part of a variable name.
BTW, name is a property of Window.name. if this is used you need to rename this value as well.
const { name, 'last-name': lastName } = { name: 'foo', 'last-name': 'bar' };
console.log(lastName);

How to access Object's property itself while defining it? [duplicate]

This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 4 years ago.
I am trying to dynamically use the previous property's value for calculation of next property.
I have a function like this in Typescript:
MacroGenerator(calories) {
this.caloriedata['macroarray'] = [
{
name: 'Low Carb, High Fat',
pmacro: (Math.round(calories*220.46226218100)/100),
pcals: (4*this.caloriedata['macroarray'][0].pmacro), // THIS IS HOW I TRIED ACCESSING THE PROPERTY AND GETTING ERROR
fcals: (calories*0.3),
fmacro: (Math.round(this.caloriedata['macroarray'][0].fcals/9)/100),
ccals: (calories-this.caloriedata['macroarray'][0].pcals-this.caloriedata['macroarray'][0].fcals),
cmacro: (Math.round(this.caloriedata['macroarray'][0].ccals/4)/100),
}
]
}
I suppose the object isn't instantiated as of when I am trying to access.
Is there any way to access it?
You can use Javascript Getters
From MDN
Sometimes it is desirable to allow access to a property that returns a
dynamically computed value, or you may want to reflect the status of
an internal variable without requiring the use of explicit method
calls. In JavaScript, this can be accomplished with the use of a
getter
var obj = {
a: 4,
get b() {
return this.a * 2;
}
}
console.log(obj.b)

Translating literal object into object's properties [duplicate]

This question already has answers here:
How to duplicate object properties in another object? [duplicate]
(16 answers)
Closed 8 years ago.
Given this object:
var myObject = {name: 'David', date: '11/13/2014'};
I want my constructor to set its object properties based on myObject:
function myClass(_object){
// set given object's properties here
}
I want to set the properties through a loop, so I wont have to set every property by hand - because the object will be dynamic.
I'm looking for a cross-browser solution.
Perhaps what you want is this:
function MyClass(_object) {
for (var p in _object) {
if (_object.hasOwnProperty(p)) {
this[p] = _object[p];
}
}
}
Don't forget to use new:
var obj = new MyClass(myObject);
Fiddle

Create javascript object using constants with dots as property [duplicate]

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Variable as the property name in a JavaScript object literal? [duplicate]
(3 answers)
Closed 8 years ago.
I have an object holding some of my program constants so that I can use it in all of the source code files. The constants object is something like this:
CONSTANTS = {
THING_TYPE: 'type',
THING_INFORMATION: 'information',
THING_DESCRIPTION: 'description',
THING_NAME: 'name',
manyOtherConstants
}
And I want to create objects using a similar notation and using the value of the constants as a property of the object; this is what I'm trying to do:
var myObject = {
CONSTANTS.THING_TYPE: 'whateverType',
CONSTANTS.THING_INFORMATION: {
CONSTANTS.THING_DESCRIPTION: 'whateverDescription',
CONSTANTS.THING_NAME: 'whateverName',
}
}
The problem is that I cannot use the constants in that way. Javascript says:
'SyntaxError: missing : after property id'
Is there any way of doing what I am trying to do using that notation? Or is the only thing that I can do is the following?
var myObject = {}
myObject[CONSTANTS.THING_TYPE] = 'whateverType';
myObject[CONSTANTS.THING_INFORMATION] = {};
myObject[CONSTANTS.THING_INFORMATION][CONSTANTS.THING_DESCRIPTION] = 'whateverDescription';
myObject[CONSTANTS.THING_INFORMATION][CONSTANTS.THING_NAME] = 'whateverName';
No you cannot do that using object literal initialization syntax.
So the only way is to use what you do in the second case - using [...] notatin.

Categories