Spread operator with bracket notation [duplicate] - javascript

This question already has answers here:
Object destructuring with property names that are not valid variable names
(2 answers)
Closed 3 years ago.
The following works fine:
const o = {one:1,two:2,three:3};
const {one,...others}=o;//one=1, others={two:2,three:3}
But how would I do the following:
var o = {['this-is-one']:1,two:2,three:3};
var {['this-is-one'],...others}=o;
Currently that gives me a SyntaxError: Unexpected token ','
I suspect it would not work because this-is-one would be invalid for a constant name (it only works for property values).

You need a renaming of the variable name, because the the given key is not a valid variable name.
var o = { 'this-is-one': 1, two: 2, three: 3 },
{ 'this-is-one': thisIsOne, ...others } = o;
console.log(thisIsOne);
console.log(others);

Related

why does it not giving error without quotes? [duplicate]

This question already has answers here:
What is the difference between object keys with quotes and without quotes?
(5 answers)
Should Javascript Objects keys be quoted in?
(3 answers)
Closed 2 years ago.
Here upperLeft and lowerRight are not in quotes but why it does not raise any error ?
example:-
Object literals can be nested. For example:
var rectangle = { upperLeft: { x: 2, y: 2 },
lowerRight: { x: 4, y: 5 } };
this is about object initializer in javascript.
Object can have keys only as string or symbol, anything else then these will be converted to string internally.
Object internally converts its keys to string, so 1 and "1" both are same. So here upperLeft and lowerLeft doesn't throw any error here because it treats them as string only
let obj = {
1: '1',
hey: 'hey'
}
console.log(obj["1"])
console.log(obj[1])
console.log(obj[1] === obj['1'])
The expression in object initialiser are evaluated during initialisation so you can use any expression to have a dynamic key or value.
let key = 'key'
let newKeyValue = "Some value"
const obj = {
[key] : 'some value',
[1 + 2] : 'some more value',
newKey: newKeyValue
}
console.log(obj)
Legal identifiers means anything which follows the following rules
Identifier should have only alphabets, numbers, $ and _
First character should not be number
But in object keys you can use any legal string it will work where as while defining variable you can't use reserved words and illegal identifiers
const obj = {
"1abc" : 'some value'
}
console.log(obj['1abc'])
const do = "no you can't"
Note:- To access invalid identifier you need to use [] bracket notation

Using a string to call an object [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 3 years ago.
I am trying to create a program that defines the variable finalResult based on variable input. The input variable should call on an object inside of object A:
var input = "";
var A = {
AA: {
result: 0
},
AB: {
result: 1
}
}
var finalResult = A.input.result;
So if input = "AA", then the final result should be 0, but if input = "AB", then the final result should be 1.
You can do A[input].result, which assumes the value of input is present as a property in A. If the property isn’t present you’ll get an error trying to access result on undefined. You can guard against this by OR’ing it with an empty object:
(A[input] || {}).result // undefined if A[input] isn’t present

Accessing an element of a nested object using a variable for the key? [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 7 years ago.
Silly example:
<script>
var a = {
'b' : {
'c' : "success!!"
}
};
var d = 'b.c';
</script>
How could I access success!! if I can't go for the obvious solution a.b.c or a['b']['c'], but instead have to use d? I tried a[d], which doesn't seem to do the trick. I also tried to fiddle with eval(). Is this even possible?
If it's really necessary to have the keys in a string separated with a dot, I would use split and reduce:
var success = d.split(".").reduce(function (obj, key) {
return obj[key];
}, a);
Try splitting
var a = {
'b' : {
'c' : "success!!"
}
};
var d = 'b.c';
var splat = d.split('.');
console.log(a[splat[0]][splat[1]]);

Getting an object with a variable. -javascript- [duplicate]

This question already has answers here:
How to use variables in dot notation like square bracket notation
(6 answers)
Closed 8 years ago.
var i = "test";
var test1 = {
test: 3,
b: 3
};
console.log(test1.i);
Sorry if it's a simple answer, I am still learning.
var i is looping to something different every few seconds and var i will always be something on test1.
If you are trying to retrieve a property of an object you can use the . notation, or the [] notation
var test1 = {
test: 3,
b: 3
};
Using . notation
test1.test; // -> returns 3
Using [] notation
var propertyName = 'test'
test1[propertyName]; // -> returns 3
Do it this way:
var test1 = {
test : 3
};
console.log(test1[i])

jQuery expression as object key [duplicate]

This question already has answers here:
How to create an object property from a variable value in JavaScript? [duplicate]
(9 answers)
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 8 years ago.
I need to figure out how to create a dynamic key string for an object. This expression makes JavaScript complain.
return {$(this).val(): true}; // returns an object e.g. {2: true}
What am I doing wrong?
You have to create the object, then use bracket notation for the dynamic key
var obj = {};
var val = $(this).val();
obj[val] = true;
return obj;
or a completely unnecessary one-liner
return (function(o,e) {o[e.value]=true; return o;})({}, this);
The JavaScript object literal syntax {x: y} specifies that x will be a (possibly) quoteless string, and y any value. You can't use this syntax for dynamic keys.
Use this instead:
var foo = {};
foo[$(this).val()] = true;
return foo;

Categories