Colon after an array in javascript - javascript

does anyone know what this syntax is in Javascript?
I got a function like so:
function myFunc(param) {
return {
[var.prop]: param.func(args);
};
}
That looks like a colon after an array. Would anyone know what that means in JS?
Thanks.

In normal the object with key we know will be look like,
function myFunc() {
const newObj = {
'key': 'value'
}
return newObj;
}
console.log(myFunc());
In the above you can able to see that the 'key' act as a known string.
Suppose in your app if you get that string in dynamic format then you can add square bracket around like [] and can assign value of that property as a key to an object.
For eg.., You are getting the key from an object like,
const data = {
prop:'dynamicKey'
};
And you need to assign the value of prop as key to an obj then you can use it like,
[data.prop]: 'value'
const data = {
prop:'dynamicKey'
};
function myFunc() {
const newObj = {
[data.prop]: 'value'
}
return newObj;
}
console.log(myFunc());

Related

Pulling dynamic values from JavaScript object

I want to destructure a dynamic key from a object, where `key` is some pattern. There is counter appended to key.
var obj = {
"key2":{"left":{"content": "This data to be pulled"}},
"hasErrorcharges2":false,
"hasErrorcharges2_Card":""
}
const {key2: {left: content }} = obj;
Here key2 is dynamic. So we know that it will always start with key and the other values can be key0, key1, key3 and hence forth. How do we traverse in this case?
Things tried.
Match the if object has any key similar to it. and then return the matched key. but got true false
can't destructure dynamic prop. but in this we know a pattern
traverse through the object with dynamic property and get the value.
expecting to write a similar function like hasOwn() or hasOwnProperty
You can't do the destructuring until you know the name of the property. You can find it by using find on Object.keys (but keep reading for an alternative). Then you can use computed property notation to specify that name in the destructuring expression. (There's also a small error in that expression, see the highlighted bit below.)
const keyName = Object.keys(obj).find((key) => key.startsWith("key"));
if (keyName) {
const {
// vvvvvvvvv−−−−−−−−−−−−−−−−−−−−−−−−−− computed property notation
[keyName]: { left: { content } },
// ^−−−−−−−−−^−−−−− minor correction to destructuring
} = obj;
// ...
}
There I've just checked that the property name starts with key — you might want to beef up the condition in the find callback, but that's the general idea.
Live Example:
const obj = {
key2: { left: { content: "This data to be pulled" } },
hasErrorcharges2: false,
hasErrorcharges2_Card: "",
};
const keyName = Object.keys(obj).find((key) => key.startsWith("key"));
if (keyName) {
const {
[keyName]: { left: { content } },
} = obj;
console.log(`content = ${content}`);
}
That said, if you need to loop through the object properties anyway, it may not be worth setting yourself up for destructuring vs. just grabbing the property in a loop and breaking when you find it:
let content = null;
for (const key in obj) {
if (key.startsWith("key")) {
content = obj[key].left.content;
break;
}
}
if (content !== null) { // Valid only if we know content won't be `null` in the object
// ...
}
Live Example:
const obj = {
key2: { left: { content: "This data to be pulled" } },
hasErrorcharges2: false,
hasErrorcharges2_Card: "",
};
let content = null;
for (const key in obj) {
if (key.startsWith("key")) {
content = obj[key].left.content;
break;
}
}
if (content !== null) { // Valid only if we know content won't be `null` in the object
console.log(`content = ${content}`);
}
If you like, this:
content = obj[key].left.content;
could be:
({ content } = obj[key].left);
...which avoid repeating the identifier content. Or even:
({left: { content }} = obj[key]);
...though there's really no need to use the nested destructuring, it doesn't save you anything. :-)
(We need the () around it because otherwise the { at the beginning looks like the beginning of a block to the JavaScript parser.)

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

JavaScript request object- convert key as a variable to string

I'm a programming beginner.
API post call accepts object variable (derived from variable) as a string as follows
"option":
{
"235": “30”
},
{
"238": “32”
}
My code angular 6
option = [];
---
this.option.push({
[option.product_option_id]: $event
});
which result
option = [ {
235: 30
}]
but need this variable in double-quoted "235".
please help
but need this variable in double-quoted "235"
By which you mean that you need it to be a string.
Don't worry, it is. When you use a number as a property name, it's converted to a string automatically. Property names can only be strings or Symbols, so things that aren't strings or Symbols get converted to string:
class Example {
constructor() {
this.option = [];
const option = {
product_option_id: 42
};
const $event = {};
this.option.push({
[option.product_option_id]: $event
});
const pushed = this.option[0];
for (const key of Object.keys(pushed)) {
console.log(`${key}: ${typeof key}`);
}
}
}
new Example();
That said, the expression within the [] of a computed property name is just that: an expression. So if you wanted to be explicit, you could use String there:
option.push({
[String(option.product_option_id)]: $event
});

Get an object just by a property value

Let´s assume I have an object property which is passed into a function. In this case 'name' is filled with 'myObject.name' (which has the value 'Tom') - so basically 'Tom' gets passed into the function as the 'name'
function(name) {
do something //non-essential for my question
}
Is it possible to get the object, where 'Tom' is the property of, just by having the information 'Tom'? Basically I´m looking to get myObject.
Thanks :)
No, that's not possible.
All that the function knows is that one of its parameters was pointed to the string "Tom", not what else points to that string somewhere else in memory.
You can store objects within an array, filter the array to match property name of object to parameter passed to function using for..of loop, Object.entries(), which returns an array of property, values of an object.
const data = Array();
const setObjectPropertyName = _name => {
data.push({[_name]:_name});
return data
}
const getObjectByPropertyName = prop => {
let res = `${prop} property not found in data`;
for (let obj of data) {
for (let [key] of Object.entries(obj)) {
if(key === prop) return obj;
}
}
return res;
}
let s = setObjectPropertyName("Tom");
let g = getObjectByPropertyName("Tom");
let not = getObjectByPropertyName("Tome");
console.log(s,"\n", g, "\n", not);
Disclaimer: you absolutely should not do this. I'm only posting this because it is in fact possible (with some caveats), just really not advisable.
Going on the assumption that this is running in the browser and it's all running in the global scope (like in a script tag), you could technically iterate over the window object, check any objects in window for a name property and determine if their name property matches the name passed to your function.
var myObject = {
name: 'Tom',
thisIs: 'so awful',
imSorry: true,
};
function doSomethingWithName(name) {
for (var obj in window) {
var tmp = window[obj];
if (Object(tmp) === tmp && tmp.name === name) {
return tmp;
}
}
}
console.log(doSomethingWithName(myObject.name));

Set an object property by using its value [duplicate]

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

Categories