Property Name gets lost? [duplicate] - javascript

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.

Related

How do i access an object's key but i want to pass the key as a variable [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 1 year ago.
for example:
object = {
name: "Mike",
age: 15
}
object.age // returns 15 right?
But I want to pass the 'age' key as a variable name:
object = {
name: "Mike",
age: 15
}
const age = 10.toString()
How do I get the result of something like this:
object.`${age}`
Try
object["age"]
or
var propName='age'
object[propName]
You can simply do this by
object[age]
Properties can be accessed by either . (dot notation) or via brackets []
that is:
object[key_name]
// where key_name is a variable
object["some_key"] // {"some_key":"value"} or {some_value:"value"}
object[19] // {19:"some_value"}
You can use object destructuring like;
var object = { name: "Mike"
, age : 15
},
{age} = object;
console.log(age);

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 }

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);

Using Variable for Property Name of Object - Javascript [duplicate]

This question already has an answer here:
How to use the value of a variable in creating an object in JavaScript [duplicate]
(1 answer)
Closed 9 years ago.
saw a few answers related to this, but none answer this version of the subject in question.
Consider the following: (linkto: jsfiddle)
$(function(){
arrKeys = [];
objArr = [];
nameArr = ['name1','name2','name3','name4'];
descArr = ['desc1','desc2','desc3','desc4'];
allValues = {name: nameArr, desc: descArr};
arrKeys[0] = 'name';
arrKeys[1] = 'desc';
first = arrKeys.shift(); // returns 'name'
$(allValues[first]).each(function (key,value) {
console.log(first); //returns 'name'
objArr[key] = {first:value}; //the problem
});
console.log(objArr);
});
With console.log(objArr) producing the following array of objects like so:
[Object, Object, Object, Object]
0: Object
first: "name1"
1: Object
first: "name2"
2: Object
first: "name3"
3: Object
first: "name4"
length: 4
The issue is that I'd like the property "first" to be the value of the var first (which is "name".. So instead, the result would be:
[Object, Object, Object, Object] 0: Object
name: "name1" 1: Object
name: "name2" 2: Object
name: "name3" 3: Object
name: "name4" length: 4
(linkto: jsfiddle)
To set variables as key names you have to use bracket notation;
console.log(first); // returns 'name'
var obj = {};
obj[first] = value;
objArr[key] = obj; // no longer a problem
Sorry it's more verbose :(
Edit;
In ES6 you can now use computed-property-names;
const key = 'name';
const value = 'james';
const obj = {
[key]: value
};
var x = {}
x[first] = value
objArr[key] = x
Javascript object literal syntax treats unquoted keys as if they were quoted strings instead of variable names. You have to use bracket syntax to set properties with names computed at runtime.
(Why are you wrapping your code in a jQuery call? And you really should be using var declarations.)

Categories

Resources