Set an object property by using its value [duplicate] - javascript

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.
Say I call following function:
var query = makeQuery("email", "foo#bar.com");
The implementation I have is:
makeQuery = function (key, value) {
return { key: value};
}
The object I end up with is: {"key": "foo#bar.com"}, which is obviously wrong. I would like to obtain {"email": "foo#bar.com"} instead. I tried setting it like so:
makeQuery = function (key, value) {
return { JSON.stringify(key): value};
}
... but I get a "SyntaxError: Unexpected token ." I've also thought of using toString() and even eval(), without success. So my problem is to be able to set the property of the object returned in makeQuery() using its real value, that is, pick up the value of 'key', not setting the property with the 'key' literal.
Thanks for the help.

Create the object first and then use the square bracket syntax so you can set the property using the value of key:
makeQuery = function (key, value) {
var query = {};
query[key] = value;
return query;
};

For variable keys in objects, use
var obj[key] = value
So then it becomes:
function makeQuery(key, value) {
var obj = {};
obj[key] = value;
return obj;
}

define an object..
makeQuery = function (key, value) {
var o = {};
o[key] = value;
return o;
}

Related

Setter for anything in JavaScript [duplicate]

This question already has answers here:
Is it possible to implement dynamic getters/setters in JavaScript?
(5 answers)
Closed 3 years ago.
I have an object, let's call it obj, it looks like this:
const obj = {
key: "value"
}
Now I want to do something when a property is set. I heard about setters,
that I can use by doing:
const obj = {
set key(e) {
console.log("Property key has been set!")
}
}
But I want to do this, for any property... Like instead of only for key, it would be for anything, example:
obj.SomeKey = "value"
Should log "Property key has been set!"
and it would be the same for any property...
Is there a way in JavaScript to do this? Thanks
You could create a ES6 Proxy, which allows you to modify the set method like so:
const obj = {
key: "value"
};
const objProxy = new Proxy(obj, {
set: (obj, prop, v) => {
obj[prop] = v;
console.log("do something");
}
});
objProxy.name = "foo";
console.log(objProxy); // Proxy now has name attribute
console.log(obj); // And so does the original object

Getting the value of a specific key in an object through a function [duplicate]

This question already has answers here:
How can I get the index of an object by its property in JavaScript?
(22 answers)
Closed 4 years ago.
As an exercise, I am trying to write a function called getValue() which takes two parameters, obj and key.
This is unrelated to getting an index of an object by its property.
The function should pass in the name of an object (obj) and the name of an object property (key), the return the value associated with that property. If there is no value (that is, the property does not exist in the object), getValue() should return undefined. As long as the named property does exist, the function should return its associated value.
I wrote a function that works but only if the property is named key. Which of course is not what I had in mind.
function getValue(obj, key) {
this.obj = {};
this.key = obj.key;
const val = function() {
return obj.key;
};
return val();
}
var theObject = {nokey: 'my_value'};
var output = getValue(theObject, 'nokey');
console.log(output);
// --> 'should return 'my_value' but
// but returns undefined
Since you're passed the object itself, just access the property with bracket notation:
function getValue(obj, key) {
return obj[key];
}
var theObject = {nokey: 'my_value'};
console.log(getValue(theObject, 'nokey'));
var object2 = {foo: 'bar'};
console.log(getValue(object2, 'baz'));

JavaScript: remove all but 1 key from an object [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 5 years ago.
I have an object and I want to remove all values except the one that matches a particular key. For example, I could do this:
function remove(obj, key) {
var value = obj[key]
var ret = {}
ret[key] = obj[key]
obj = ret
}
Or I could iterate:
for (var k in obj) {
if (k != key) {
delete obj[k]
}
}
But I'm wondering if there's a better way. Creating a temporary variable and iterating over the entire object both seem unnecessary. My initial attempt was:
obj = {
key: obj[key]
}
But that resulted in an object with a key of key.
You can indeed achieve what you described without using temporary variables.
function remove(obj, key) {
return Object.assign({}, { [key] : obj[key]});
}
You can just create a new object with [key]:obj[key].
var obj = {
"a":1,
"b":2
};
var key = "a";
function filterByKey(object, key) {
return Object.create({[key]:obj[key]});
}
function filterByKey2(object, key) {
return {[key]:obj[key]};
}
console.log(filterByKey(obj, key));
console.log(filterByKey2(obj, key));

Can I extend object dynamically by using a dynamic key and object as a value?

Let's say I have this function:
var obj = {};
extend('myKey', 'myVal', 'mySomething');
function extend(key, val, something){
$.extend(obj, {
key : {
value: val,
something: something
}); // key is set as "key" and not as the key real value
// I want obj to now have a key which is 'myKey'
// and a value which is an object:
// {value:'myVal', something:'mySomething'}
}
Could this be accomplished somehow?
I would like to do it without creating a new object in the extend function.
var obj = {};
extend('myKey', 'myVal', 'mySomething');
function extend(key, val, something){
obj[key] = {value:val, something:something};
}
//this line is just to show the result of the function, not part of the solution.
document.body.innerHTML += JSON.stringify(obj);
Just use plain JavaScript for this. You can assign a key to an object using the bracket notation. This way you can set it to a variable you defined.
If you are just trying to add properties to obj, you can do this:
function addProp(obj, key, value) {
obj[key] = value;
}

Creating object with dynamic keys [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 8 years ago.
First off, I'm using Cheerio for some DOM access and parsing with Node.js. Good times.
Heres the situation:
I have a function that I need to create an object. That object uses variables for both its keys and values, and then return that single object. Example:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value');
return { key : value }
})
callback(null, inputs);
}
It outputs this:
[ { key: '1' }, { key: '1' } ]
(.map() returns an array of objects fyi)
I need key to actually be the string from this.attr('name').
Whats the best way to assign a string as a key in Javascript, considering what I'm trying to do?
In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys: Object Initializer spec.
The syntax is:
var obj = {
[myKey]: value,
}
If applied to the OP's scenario, it would turn into:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
return {
[this.attr('name')]: this.attr('value'),
};
})
callback(null, inputs);
}
Note: A transpiler is still required for browser compatiblity.
Using Babel or Google's traceur, it is possible to use this syntax today.
In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.
To use a "dynamic" key, you have to use bracket notation:
var obj = {};
obj[myKey] = value;
In your case:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value')
, ret = {};
ret[key] = value;
return ret;
})
callback(null, inputs);
}
You can't define an object literal with a dynamic key. Do this :
var o = {};
o[key] = value;
return o;
There's no shortcut (edit: there's one now, with ES6, see the other answer).

Categories