Creating an object with dynamic keys [duplicate] - javascript

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 7 years ago.
Here is a function building an object dynamically:
function onEntry(key, value) {
console.log(key) // productName
console.log(value) // Budweiser
const obj = { key: value }
console.log(obj) // { key: "Budweiser" }
}
Expected output is
{ productName: "Budweiser" }
But property name is not evaluated
{ key: "Budweiser" }
How to make property name of an object evaluated as an expression?

Create an object, and set its key manually.
var obj = {}
obj[key] = value
Or using ECMAScript 2015 syntax, you can also do it directly in the object declaration:
var obj = {
[key] = value
}

Related

Odd syntax for setting an object's property in JavaScript [duplicate]

This question already has answers here:
What does this symbol mean in JavaScript?
(1 answer)
What do square brackets around a property name in an object literal mean?
(2 answers)
Closed 3 months ago.
What is happening in the code on line 10 ({[last]: newObj}) in the following snippet:
How is JS able to use the value of parameter last instead of using last as the property name?
let first = 'first';
let last = 'last';
function foo(first, last) {
let newObj = {
name: 'newObj'
};
let obj = {};
Object.assign(obj, {[last]: newObj});
return obj;
}
console.log(foo('bye', 'hey')); // { hey: { name: 'newObj' } }
Thanks.

Why is my JavaScript object function assigning its parameter name as the key instead of the argument name? [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 2 years ago.
I'm fairly new to Javascript Object. I've defined a non-destructive function to update an object like this:
function updateObjectWithKeyAndValue(object, key, value) {
return Object.assign({}, object, { key: value });
}
let object = {a: 1};
console.log(updateObjectWithKeyAndValue(object, 'b', 2));
console.log(object);
I'm getting the return value of the function as { a: 1, key: 2 } instead of { a: 1, b: 2 }. Is there something I'm not doing right? Thanks...
{ key: value } is an object with a property named “key”. To name the property according to the value in the variable key, use a computed property name:
{ [key]: value }
If your JavaScript environment supports object spread, the whole thing can be written as:
return { ...object, [key]: value };

JSON Object key value pair function [duplicate]

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 3 years ago.
Why i am unable to pass "abc" to someKey
function convertToKeyValuePair(someKey,someValue){
var map = {someKey : someValue};
return JSON.stringify(map);
}
print(convertToKeyValuePair("abc","xyz"));
O/P = {"someKey":"sdfdf"}
Expected O/P = {"abc":"xyz"}
As you’re passing key dynamically so you’ve to use bracket around it like:
{ [someKey]: someValue }
You want dynamic keys.
let key = 'yo';
let obj = {key: 0}; // creates {"key": 0}
let objDynamic = {[key]: 0}; // creates {"yo": 0};
console.log(obj);
console.log(objDynamic);
As answered by the comment of #junvar, passing keys to objects without quotes is syntactic sugar and both of the following examples will give the same result:
{ "someVar": someValue }
{ someVar: someValue }
To use the value of a variable as a key you have to use square brackets as in:
{ [someVar]: someValue }

Property Name gets lost? [duplicate]

This question already has answers here:
Variable as the property name in a JavaScript object literal? [duplicate]
(3 answers)
Closed 4 years ago.
I am working on a pre-boot camp coding problem. I am passing in an object (ourDog) and a key (fiendly) into a function that creates a new property (key:value pair) and assigns a value of true to that key.
Looking at the output, the property is added, but the key does not have the assigned value of 'friendly', it has the parameter name of key. I expected the key:value pair to (friendly: true). Here is the code.
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"]
};
function addProperty(anObject, key) {
anObject.key = true;
return anObject;
};
var output = addProperty(ourDog, 'friendly');
console.log(output);
{name: "Camper", legs: 4, tails: 1, friends: Array(1), key: true}
Change it from dot notation to brackets.
function addProperty(anObject, key) {
anObject[key] = true;
return anObject;
};
Dot notation is used to access an object's properties when the property is a valid JavaScript identifier. Since 'friendly' is a string, you need to use brackets.

Destructing assignment with dots in property [duplicate]

This question already has answers here:
How to destructure object properties with key names that are invalid variable names?
(3 answers)
Closed 5 years ago.
I have an object like this:
const myObject = { 'docs.count': 1000, uuid: 11244, 'pri.store.size': 2453 }
I would like to do a destructuring assignment. Is that only possible for this type of fields?
const { uuid } = myObject;
Thanks!
Variable names can't include a dot, so you can't get do const docs.count = 1000, for example. Destructuring allows you to extract the values even if the property name can't be a the name of a variable, but you'll need to assign them a valid variable name:
const myObject = { 'docs.count': 1000, uuid: 11244, 'pri.store.size': 2453 }
const { 'docs.count': docsCount } = myObject;
console.log(docsCount);

Categories

Resources