Is it possible to change nested object properties with this syntax [duplicate] - javascript

This question already has answers here:
Dynamically set property of nested object
(28 answers)
Closed 5 years ago.
Say you have this object:
myObj = { foo: { bar : 123, baz: 456 } };
To edit the value of bar you can do this:
myObj['foo']['bar'] = 789
But what if you have a method somewhere that changes specific object properties like this:
myObj[key] = value
If you need to use that and you want to edit bar in the myObj object, is it possible with that code?
I tried:
myObj["foo"."bar"] = 789;
myObj["foo"["bar"]] = 789;
But it doesn't work. Is it possible at all to do?

Pure JavaScript doesn't allow you to access nested properties with a simple string.
An alterative can be i.e. lodash:
_.get(myObj, 'foo.bar'); // 123
_.set(myObj, 'foo.bar', 789);

Related

What's the difference between two ways of adding property to an existing js object? [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 3 years ago.
Let's say we need to add a property to an existing js object
var billingData = {}
In my case, I want to store input value in the js object
Here's the basic input
<input type="text" class="form-control" id="billingFullName">
We, basically, have two ways to add the property to the js object:
The first one:
billingData["billingFullName"] = document.getElementById('billingFullName').value
And the second one:
billingData.billingFullName = document.getElementById('billingFullName').value
What's the difference between them?
I'm asking, because when I was submitting the js object using AJAX to MVC Controller, where properties where added using the [] notation, the model in the Controller appeared to be null. Whereas, the dot notation appeared to solve the issue and I'm wondering why..
Typically you use bracket notation when you need to define a property dynamically such as with a variable or if the key is not in proper format for dot notation:
const obj = {}
const someKey = 'key'
obj[someKey] = 'somevalue'
console.log(obj.key) // 'somevalue'
console.log(obj.someKey) // undefined
Dot notation is when you already know the key:
const obj = {}
object.key = 'someValue'

How to use a dynamic value for object's field? [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 3 years ago.
I have an object SentimentScore as such
SentimentScore:
{Mixed: 0.00005830301233800128,
Negative: 0.0011920471442863345,
Neutral: 0.9854754209518433,
Positive: 0.013274261727929115}
I want the values based on what I have set in a variable, for eg:
var finalSentiment1 = 'Neutral';
var finalSentiment2 = 'Positive';
I want to use the variables instead, to find the values of fields of the SentimentScore.
Something like, SentimentScore.finalSentiment1 should give 0.0011920471442863345.
Is it possible without using a conditional statement? If yes, how? Thanks in advance.
You can use computed ([]) property which will allow you to have an expression to be computed as a property name on an object dynamically:
var SentimentScore = {
Mixed: 0.00005830301233800128,
Negative: 0.0011920471442863345,
Neutral: 0.9854754209518433,
Positive: 0.013274261727929115
}
var finalSentiment1 = 'Neutral';
var finalSentiment2 = 'Positive';
console.log(SentimentScore[finalSentiment1]);
console.log(SentimentScore[finalSentiment2]);

remove property on object if its' key is present on array that contains keys? [duplicate]

This question already has answers here:
One liner to delete multiple object properties
(3 answers)
Closed 3 years ago.
I have an array of keys that can be present as propert on object, if present, I want to remove those properties on it, I know removing a single prop on object like this:
const { 'removedPropOnObj', ...newObj } = obj;
newObj here becomes new object with removed property of removedPropOnObj, i want to do something like that but i have in this case is array of keys like:
['removeKey1','removeKey2','removeKey3']
Help?
You can do that using Object.keys and reduce()
let rmKeys =['removeKey1','removeKey2','removeKey3']
let obj = {
removeKey1:1,
removeKey2:2,
removeKey3:3,
removeKey4:4,
removeKey5:5
}
let newObj = Object.keys(obj).reduce((ac,a) => !rmKeys.includes(a) ?({...ac,[a]:obj[a]}) : ac,{})
console.log(newObj);

Get the value from an object when you don't know the keys [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 6 years ago.
I am passed an object lets say called myobj.
Key: last, Value: "Yellow"
To get the key it is
Object.keys(myobj) // = ["last"]
To get the value it is
myobj.last // = "Yellow"
But I want to handle any key.
So in pseudo code I want to combine these.
myobj.Object.keys(myobj) // to return "Yellow" or whatever the incoming key of the object is.
You can use square bracket notation to access object property
var myobj = {
last: "yellow"
};
var res = myobj[Object.keys(myobj)[0]];
document.write(res);

get value with string key in javascript [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 9 years ago.
I can't figure out how to get an object property using a string representation of that property's name in javascript. For example, in the following script:
consts = {'key' : 'value'}
var stringKey = 'key';
alert(consts.???);
How would I use stringKey to get the value value to show in the alert?
Use the square bracket notation []
var something = consts[stringKey];
Javascript objects are like simple HashMaps:
var consts = {};
consts['key'] = "value";
if('key' in consts) { // true
alert(consts['key']); // >> value
}
See: How is a JavaScript hash map implemented?

Categories

Resources