I want to select a random XPath from the defined Array - node.js

editMethod(){
var num = Math.floor((Math.random() *4) + 1);
var xPath_arr= [
'//android.widget.RadioButton[#text="seat1"]',
'//android.widget.RadioButton[#text="seat2"]',
'//android.widget.RadioButton[#text="seat3"]',
'//android.widget.RadioButton[#text="Notselected"]',
]
xPath_arr[num]
}
Then calling in another function like this
selectseat(){
this.editmethod();
this.doneBtn.click();
}
tried different method but received different errors like
but its not working
TypeError: Cannot read property '2' of undefined

const editMethod = () => {
let num = Math.floor((Math.random() * 3) + 1);
console.log(num)
let xPath_arr = [
'//android.widget.RadioButton[#text="seat1"]',
'//android.widget.RadioButton[#text="seat2"]',
'//android.widget.RadioButton[#text="seat3"]',
'//android.widget.RadioButton[#text="Notselected"]',
]
return xPath_arr[num];
}
// Then calling in another function like this
const selectseat =() => {
let seatElement = editMethod();
console.log(locator);
}
selectseat();
Note:
Math.random() * 3 it should be because your array contains 4 elements only.

Related

Can't write and read from chrome.storage.local in popup, how to fix? [duplicate]

Why does the following work?
<something>.stop().animate(
{ 'top' : 10 }, 10
);
Whereas this doesn't work:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
To make it even clearer: At the moment I'm not able to pass a CSS property to the animate function as a variable.
{ thetop : 10 } is a valid object literal. The code will create an object with a property named thetop that has a value of 10. Both the following are the same:
obj = { thetop : 10 };
obj = { "thetop" : 10 };
In ES5 and earlier, you cannot use a variable as a property name inside an object literal. Your only option is to do the following:
var thetop = "top";
// create the object literal
var aniArgs = {};
// Assign the variable property name with a value of 10
aniArgs[thetop] = 10;
// Pass the resulting object to the animate method
<something>.stop().animate(
aniArgs, 10
);
ES6 defines ComputedPropertyName as part of the grammar for object literals, which allows you to write the code like this:
var thetop = "top",
obj = { [thetop]: 10 };
console.log(obj.top); // -> 10
You can use this new syntax in the latest versions of each mainstream browser.
With ECMAScript 2015 you are now able to do it directly in object declaration with the brackets notation:
var obj = {
[key]: value
}
Where key can be any sort of expression (e.g. a variable) returning a value.
So here your code would look like:
<something>.stop().animate({
[thetop]: 10
}, 10)
Where thetop will be evaluated before being used as key.
ES5 quote that says it should not work
Note: rules have changed for ES6: https://stackoverflow.com/a/2274327/895245
Spec: http://www.ecma-international.org/ecma-262/5.1/#sec-11.1.5
PropertyName :
IdentifierName
StringLiteral
NumericLiteral
[...]
The production PropertyName : IdentifierName is evaluated as follows:
Return the String value containing the same sequence of characters as the IdentifierName.
The production PropertyName : StringLiteral is evaluated as follows:
Return the SV [String value] of the StringLiteral.
The production PropertyName : NumericLiteral is evaluated as follows:
Let nbr be the result of forming the value of the NumericLiteral.
Return ToString(nbr).
This means that:
{ theTop : 10 } is the exact same as { 'theTop' : 10 }
The PropertyName theTop is an IdentifierName, so it gets converted to the 'theTop' string value, which is the string value of 'theTop'.
It is not possible to write object initializers (literals) with variable keys.
The only three options are IdentifierName (expands to string literal), StringLiteral, and NumericLiteral (also expands to a string).
ES6 / 2020
If you're trying to push data to an object using "key:value" from any other source, you can use something like this:
let obj = {}
let key = "foo"
let value = "bar"
obj[`${key}`] = value
// A `console.log(obj)` would return:
// {foo: "bar}
// A `typeof obj` would return:
// "object"
Hope this helps someone :)
I have used the following to add a property with a "dynamic" name to an object:
var key = 'top';
$('#myElement').animate(
(function(o) { o[key]=10; return o;})({left: 20, width: 100}),
10
);
key is the name of the new property.
The object of properties passed to animate will be {left: 20, width: 100, top: 10}
This is just using the required [] notation as recommended by the other answers, but with fewer lines of code!
Adding square bracket around the variable works good for me. Try this
var thetop = 'top';
<something>.stop().animate(
{ [thetop] : 10 }, 10
);
You can also try like this:
const arr = [{
"description": "THURSDAY",
"count": "1",
"date": "2019-12-05"
},
{
"description": "WEDNESDAY",
"count": "0",
"date": "2019-12-04"
}]
const res = arr.map(value => {
return { [value.description]: { count: value.count, date: value.date } }
})
console.log(res);
I couldn't find a simple example about the differences between ES6 and ES5, so I made one. Both code samples create exactly the same object. But the ES5 example also works in older browsers (like IE11), wheres the ES6 example doesn't.
ES6
var matrix = {};
var a = 'one';
var b = 'two';
var c = 'three';
var d = 'four';
matrix[a] = {[b]: {[c]: d}};
ES5
var matrix = {};
var a = 'one';
var b = 'two';
var c = 'three';
var d = 'four';
function addObj(obj, key, value) {
obj[key] = value;
return obj;
}
matrix[a] = addObj({}, b, addObj({}, c, d));
Update: As a commenter pointed out, any version of JavaScript that supports arrow functions will also support ({[myKey]:myValue}), so this answer has no actual use-case (and, in fact, it might break in some bizarre corner-cases).
Don't use the below-listed method.
I can't believe this hasn't been posted yet: just use arrow functions with anonymous evaluation!
Completely non-invasive, doesn't mess with the namespace, and it takes just one line:
myNewObj = ((k,v)=>{o={};o[k]=v;return o;})(myKey,myValue);
demo:
var myKey="valueof_myKey";
var myValue="valueof_myValue";
var myNewObj = ((k,v)=>{o={};o[k]=v;return o;})(myKey,myValue);
console.log(myNewObj);
useful in environments that don't support the new {[myKey]: myValue} syntax yet, such as—apparently; I just verified it on my Web Developer Console—Firefox 72.0.1, released 2020-01-08. I stand corrected; just wrap the thing in parenthesis and it works.
(I'm sure you could potentially make some more powerful/extensible solutions or whatever involving clever use of reduce, but at that point you'd probably be better served by just breaking out the Object-creation into its own function instead of compulsively jamming it all inline)
not that it matters since OP asked this ten years ago, but for completeness' sake and to demonstrate how it is exactly the answer to the question as stated, I'll show this in the original context:
var thetop = 'top';
<something>.stop().animate(
((k,v)=>{o={};o[k]=v;return o;})(thetop,10), 10
);
Given code:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
Translation:
var thetop = 'top';
var config = { thetop : 10 }; // config.thetop = 10
<something>.stop().animate(config, 10);
As you can see, the { thetop : 10 } declaration doesn't make use of the variable thetop. Instead it creates an object with a key named thetop. If you want the key to be the value of the variable thetop, then you will have to use square brackets around thetop:
var thetop = 'top';
var config = { [thetop] : 10 }; // config.top = 10
<something>.stop().animate(config, 10);
The square bracket syntax has been introduced with ES6. In earlier versions of JavaScript, you would have to do the following:
var thetop = 'top';
var config = (
obj = {},
obj['' + thetop] = 10,
obj
); // config.top = 10
<something>.stop().animate(config, 10);
2020 update/example...
A more complex example, using brackets and literals...something you may have to do for example with vue/axios. Wrap the literal in the brackets, so
[ ` ... ` ]
{
[`filter[${query.key}]`]: query.value, // 'filter[foo]' : 'bar'
}
ES5 implementation to assign keys is below:
var obj = Object.create(null),
objArgs = (
(objArgs = {}),
(objArgs.someKey = {
value: 'someValue'
}), objArgs);
Object.defineProperties(obj, objArgs);
I've attached a snippet I used to convert to bare object.
var obj = {
'key1': 'value1',
'key2': 'value2',
'key3': [
'value3',
'value4',
],
'key4': {
'key5': 'value5'
}
}
var bareObj = function(obj) {
var objArgs,
bareObj = Object.create(null);
Object.entries(obj).forEach(function([key, value]) {
var objArgs = (
(objArgs = {}),
(objArgs[key] = {
value: value
}), objArgs);
Object.defineProperties(bareObj, objArgs);
});
return {
input: obj,
output: bareObj
};
}(obj);
if (!Object.entries) {
Object.entries = function(obj){
var arr = [];
Object.keys(obj).forEach(function(key){
arr.push([key, obj[key]]);
});
return arr;
}
}
console(bareObj);
If you want object key to be same as variable name, there's a short hand in ES 2015.
New notations in ECMAScript 2015
var thetop = 10;
var obj = { thetop };
console.log(obj.thetop); // print 10
You can do it this way:
var thetop = 'top';
<something>.stop().animate(
new function() {this[thetop] = 10;}, 10
);
This way also you can achieve desired output
var jsonobj={};
var count=0;
$(document).on('click','#btnadd', function() {
jsonobj[count]=new Array({ "1" : $("#txtone").val()},{ "2" : $("#txttwo").val()});
count++;
console.clear();
console.log(jsonobj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>value 1</span><input id="txtone" type="text"/>
<span>value 2</span><input id="txttwo" type="text"/>
<button id="btnadd">Add</button>
You could do the following for ES5:
var theTop = 'top'
<something>.stop().animate(
JSON.parse('{"' + theTop + '":' + JSON.stringify(10) + '}'), 10
)
Or extract to a function:
function newObj (key, value) {
return JSON.parse('{"' + key + '":' + JSON.stringify(value) + '}')
}
var theTop = 'top'
<something>.stop().animate(
newObj(theTop, 10), 10
)

Svelte Store. Spread syntax is not merging - just adding

I am trying to add some brocolli to my basket in the svelte store I have created. My code adds the brocooli to the basket but then duplicates the baskets and adds a whole new basket to my store. Not sure if the problem is caused by my lack of understanding of javascript or svelte.
Desired result
Basket 1 OrangePineapple Basket 2 BananaApplePlumwalnuthazelnutnutmegbroccoli
ACTUAL RESULT
Basket 1 OrangePineapple Basket 2 BananaApplePlumwalnuthazelnutnutmeg Basket 2 BananaApplePlumwalnuthazelnutnutmegbroccoli
Link to svelte codebox where you can view and run code
https://svelte.dev/repl/80d428000a3f425da798cec3450a59d4?version=3.46.2
if you click the button you see that my basket is duplicating. I am just trying to add the brocooli to the basket.
code below
import { writable } from 'svelte/store';
export const storeBaskets = writable([
{
"name": "Basket 1",
"items": ["Orange", "Pineapple"]
},
{
"name": "Basket 2",
"items": ["Banana", "Apple","Plum","walnut","hazelnut","nutmeg"]
}
])
//Local functions
export const add = (item,basketIndex) => {
storeBaskets.update(val => {
const newItems = [...val[basketIndex].items, item]
const newBasket = {'name':val[basketIndex].name,'items':newItems}
val = [...val,newBasket]
return val
})
val = [...val,newBasket]
With this line you're copying the previous store value and adding the newBasket "on top". That's how the spread operator works with arrays
let arr = [1,2,3]
let n = 4
let arr2 = [...arr, n]
console.log(arr2) // [ 1 , 2 , 3 , 4 ]
I wonder if you might have thought of the different behaviour when spreading an object, where an already existing entry might be overriden if the key already exists
let obj = {key: 'value'}
let key = 'newValue'
let obj2 = {...obj, key}
console.log(obj2) // { key: "newValue" }
To make your code working you could replace the line by val[basketIndex] = newBasket
export const add = (item,basketIndex) => {
storeBaskets.update(val => {
const newItems = [...val[basketIndex].items, item]
const newBasket = {'name':val[basketIndex].name,'items':newItems}
val[basketIndex] = newBasket
return val
})
}
Or, instead of spreading, simply push the new value directly to the according nested array in just one line
export const add = (item,basketIndex) => {
storeBaskets.update(val => {
val[basketIndex].items.push(item)
return val
})
}
You might not need to spread, because it's an array, you'r spreading the existing items of the array and then adding the new basket to it. You can map and replace by basketIndex, like:
export const add = (item,basketIndex) => {
storeBaskets.update(val => {
const newItems = [...val[basketIndex].items, item]
const newBasket = {'name':val[basketIndex].name,'items':newItems}
return val.map((basket, i) => i === basketIndex ? newBasket : basket)
})
}
(Working example)

Discord content must be 2000 or fewer in length in a roles list

i know this error is already solved but in another form i could't solve my error:
if(msg.content.startsWith(`${prefix}roles`)) {
const spaces = ' ';
const roles = [];
msg.guild.roles.filter(r => r.name !== '#everyone').forEach(c => {
let list = roles.push(`${c.name} ${spaces.substring(c.name.length)} ${c.members.size} member`);
if(c.members.size < 2) roles.push(`${c.name} ${spaces.substring(c.name.length)} ${c.members.size} member`);
if(c.members.size >= 2) roles.push(`${c.name} ${spaces.substring(c.name.length)} ${c.members.size} members`);
});
msg.channel.send(`\`\`\` ${roles.join('\n')} \`\`\``);
}
});
Thanks.
Well that's probably because you are pushing to the array 2 times for each role
Once here:
let list = roles.push(${c.name} ${spaces.substring(c.name.length)} ${c.members.size} member);
And another time after that with the if statements,
After you change it to one time, it should fix it unless you have like 100 roles, and in which case you can just add the option split: true inside of message.channel.send
https://discord.js.org/#/docs/main/stable/typedef/MessageOptions
https://discord.js.org/#/docs/main/stable/typedef/SplitOptions
if (msg.content.startsWith(`${prefix}roles`)) {
const spaces = ' ';
const roles = [];
msg.guild.roles.filter(r => r.name !== '#everyone').forEach(role => {
let string = `${c.name} ${spaces.substring(c.name.length)} ${c.members.size} member`;
if (role.members.size >= 2) {
string += "s";
}
roles.push(string);
});
//all those escape characters look bad, just concat strings
msg.channel.send("```\n" + roles.join('\n') + "\n```", { split: true });
}

Using Node.js iterating array of object and if value matched then insert all related values in different array

INPUT
[
{"Id":1,"text":"Welcome","question":"san","translation":"willkommen."},
{"Id":1,"text":"Welcome","question":"se","translation":"bienvenida"},
{"Id":1,"text":"Welcome","question":"fr","translation":"propriétaires"},
{"Id":1,"text":"ajax","question":"san","translation":"ommen."},
{"Id":1,"text":"ajax","question":"se","translation":"bienve"},
{"Id":1,"text":"ajax","question":"fr","translation":"propires"}
]
if question = san then all "san" objects will be inserted in array like and so on-
san:[{"text":"Welcome","question":"san","translation":"willkommen.},
{"text":"ajax","question":"san","translation":"ommen."},
se:[{"text":"Welcome","question":"se","translation":"bienvenida.},
{"text":"ajax","question":"se","translation":"bienve."},
fr:[{"text":"Welcome","question":"fr","translation":"propriétaires.},
{"text":"ajax","question":"fr","translation":"propires."},
Question is how do i check if question=san then make one array and insert all san values in it and so on without hardcoding the question property values.
Tried looping things but how to match without hardcoding because in future question attribute can change .
question="san" will be all together in an array "se" will be all together in an array and so on.
New to this not know much about nodejs.
Tried something like this but not coming as required way
fs.readFile('./data.json', 'utf8', function (err,data) {
data = JSON.parse(data);
var array = [];
for(var i = 0; i < data.length; i++) {
var lang = data[i].language;
for(var j= 0; j< data.length; j++) {
if(lang == data[j].language){
array.push(data[j].language);
array.push(data[j].translation);
array.push(data[j].text);
}
}
}
output Required
san:[{"text":"Welcome","question":"san","translation":"willkommen.},
{"text":"ajax","question":"san","translation":"ommen."},
se:[{"text":"Welcome","question":"se","translation":"bienvenida.},
{"text":"ajax","question":"se","translation":"bienve."},
fr:[{"text":"Welcome","question":"fr","translation":"propriétaires.},
{"text":"ajax","question":"fr","translation":"propires."},
I recommend you to use ES6 functions instead of for. You can separate the different processes and make the code more modular and declarative. This way you can change easily the desired output since your code is made by little pieces.
const data = [
{"Id":1,"text":"hi all present ","language":"sde","translation":"Hernjd ndjjsjdj"},
{"Id":1,"text":"hi all present","language":"ses","translation":"dfks kdfk kdfk"},
{"Id":1,"text":"hi all present","language":"sfr","translation":"bsh kkoweofeo"},
{"Id":1,"text":"hi all present","language":"szh","translation":"kdijo keow"},
{"Id":1,"text":"activated","language":"sde","translation":"Konto eid ke"},
{"Id":1,"text":"activated","language":"ses","translation":"La cueweffewfefwef."},
{"Id":1,"text":"activated","language":"sfr","translation":"Cowefrwef"},
{"Id":1,"text":"activated","language":"szh","translation":"fhewjhfwh"},
{"Id":1,"text":"completed","language":"sde","translation":"Ihr fwejiewf"},
{"Id":1,"text":"completed","language":"ses","translation":"Ya hfuwifrw"},
{"Id":1,"text":"completed","language":"sfr","translation":"Votrkwfwe"},
{"Id":1,"text":"completed","language":"szh","translation":"dmksfkwkf"},
{"Id":1,"text":"ACTION","language":"sde","translation":"AKTION"},
{"Id":1,"text":"ACTION","language":"ses","translation":"ACCIONES"},
{"Id":1,"text":"ACTION","language":"fr","translation":"ACTION"}];
// Define the properties that we want to filter for each element
const filterProperties = (item) => ({
text:item.text,
language: item.language,
translation:item.translation
})
// Given a type of languages ('sde'), filter the data in function of this value
const getItemsByLanguage = (language) => {
return data.filter((item) => item.language === language)
}
const onlyUnique = (value, index, self) => {
return self.indexOf(value) === index;
}
// Get the unique values of languages: ['sde', 'ses', 'sfr', ...]
const uniqueLanguages = data.map((item) => item.language).filter(onlyUnique)
// Get all found items for a language ('sde') and get the desired format (returns array of objects)
const resultArray = uniqueLanguages.map((language) => (
{[language]: getItemsByLanguage(language).map(filterProperties)}
))
// Convert the array of objects to single object
const result = Object.assign({}, ...resultArray)
console.log(result)
const data = [
{"Id":1,"text":"hi all present ","language":"sde","translation":"Hernjd ndjjs
jdj"},
{"Id":1,"text":"hi all present","language":"ses","translation":"dfks kdfk
kdfk"},
{"Id":1,"text":"hi all present","language":"sfr","translation":"bsh kkowe
ofeo"},
{"Id":1,"text":"hi all present","language":"szh","translation":"kdijo keow"},
{"Id":1,"text":"activated","language":"sde","translation":"Konto eid ke"},
{"Id":1,"text":"activated","language":"ses","translation":"La cueweffewfef
wef."},
{"Id":1,"text":"activated","language":"sfr","translation":"Cowefrwef"},
{"Id":1,"text":"activated","language":"szh","translation":"fhewjhfwh"},
{"Id":1,"text":"completed","language":"sde","translation":"Ihr fwejiewf"},
{"Id":1,"text":"completed","language":"ses","translation":"Ya hfuwifrw"},
{"Id":1,"text":"completed","language":"sfr","translation":"Votrkwfwe"},
{"Id":1,"text":"completed","language":"szh","translation":"dmksfkwkf"},
{"Id":1,"text":"ACTION","language":"sde","translation":"AKTION"},
{"Id":1,"text":"ACTION","language":"ses","translation":"ACCIONES"},
{"Id":1,"text":"ACTION","language":"fr","translation":"ACTION"}];
// Define the properties that we want to filter for each element
const filterProperties = (data) => ({
text:data.text,
question: data.question,
translation:data.translation
})
// Given a type of question ('san'), filter the data in function of this value
const getQuestions = (question) => {
return data.filter((item) => item.question === question)
}
const onlyUnique = (value, index, self) => {
return self.indexOf(value) === index;
}
// Get the unique values of questions: ['san', 'se', 'fr']
const uniqueQuestions = data.map((item) => item.question).filter(onlyUnique)
// Get all found values for a question and get the desired format (returns
array of objects)
const resultArray = uniqueQuestions.map((question) => (
{[question]: getQuestions(question).map(filterProperties)}
))
// Convert the array of objects to single object
const result = Object.assign({}, ...resultArray)
console.log(result)

Mongoose Nested Array [duplicate]

Why does the following work?
<something>.stop().animate(
{ 'top' : 10 }, 10
);
Whereas this doesn't work:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
To make it even clearer: At the moment I'm not able to pass a CSS property to the animate function as a variable.
{ thetop : 10 } is a valid object literal. The code will create an object with a property named thetop that has a value of 10. Both the following are the same:
obj = { thetop : 10 };
obj = { "thetop" : 10 };
In ES5 and earlier, you cannot use a variable as a property name inside an object literal. Your only option is to do the following:
var thetop = "top";
// create the object literal
var aniArgs = {};
// Assign the variable property name with a value of 10
aniArgs[thetop] = 10;
// Pass the resulting object to the animate method
<something>.stop().animate(
aniArgs, 10
);
ES6 defines ComputedPropertyName as part of the grammar for object literals, which allows you to write the code like this:
var thetop = "top",
obj = { [thetop]: 10 };
console.log(obj.top); // -> 10
You can use this new syntax in the latest versions of each mainstream browser.
With ECMAScript 2015 you are now able to do it directly in object declaration with the brackets notation:
var obj = {
[key]: value
}
Where key can be any sort of expression (e.g. a variable) returning a value.
So here your code would look like:
<something>.stop().animate({
[thetop]: 10
}, 10)
Where thetop will be evaluated before being used as key.
ES5 quote that says it should not work
Note: rules have changed for ES6: https://stackoverflow.com/a/2274327/895245
Spec: http://www.ecma-international.org/ecma-262/5.1/#sec-11.1.5
PropertyName :
IdentifierName
StringLiteral
NumericLiteral
[...]
The production PropertyName : IdentifierName is evaluated as follows:
Return the String value containing the same sequence of characters as the IdentifierName.
The production PropertyName : StringLiteral is evaluated as follows:
Return the SV [String value] of the StringLiteral.
The production PropertyName : NumericLiteral is evaluated as follows:
Let nbr be the result of forming the value of the NumericLiteral.
Return ToString(nbr).
This means that:
{ theTop : 10 } is the exact same as { 'theTop' : 10 }
The PropertyName theTop is an IdentifierName, so it gets converted to the 'theTop' string value, which is the string value of 'theTop'.
It is not possible to write object initializers (literals) with variable keys.
The only three options are IdentifierName (expands to string literal), StringLiteral, and NumericLiteral (also expands to a string).
ES6 / 2020
If you're trying to push data to an object using "key:value" from any other source, you can use something like this:
let obj = {}
let key = "foo"
let value = "bar"
obj[`${key}`] = value
// A `console.log(obj)` would return:
// {foo: "bar}
// A `typeof obj` would return:
// "object"
Hope this helps someone :)
I have used the following to add a property with a "dynamic" name to an object:
var key = 'top';
$('#myElement').animate(
(function(o) { o[key]=10; return o;})({left: 20, width: 100}),
10
);
key is the name of the new property.
The object of properties passed to animate will be {left: 20, width: 100, top: 10}
This is just using the required [] notation as recommended by the other answers, but with fewer lines of code!
Adding square bracket around the variable works good for me. Try this
var thetop = 'top';
<something>.stop().animate(
{ [thetop] : 10 }, 10
);
You can also try like this:
const arr = [{
"description": "THURSDAY",
"count": "1",
"date": "2019-12-05"
},
{
"description": "WEDNESDAY",
"count": "0",
"date": "2019-12-04"
}]
const res = arr.map(value => {
return { [value.description]: { count: value.count, date: value.date } }
})
console.log(res);
I couldn't find a simple example about the differences between ES6 and ES5, so I made one. Both code samples create exactly the same object. But the ES5 example also works in older browsers (like IE11), wheres the ES6 example doesn't.
ES6
var matrix = {};
var a = 'one';
var b = 'two';
var c = 'three';
var d = 'four';
matrix[a] = {[b]: {[c]: d}};
ES5
var matrix = {};
var a = 'one';
var b = 'two';
var c = 'three';
var d = 'four';
function addObj(obj, key, value) {
obj[key] = value;
return obj;
}
matrix[a] = addObj({}, b, addObj({}, c, d));
Update: As a commenter pointed out, any version of JavaScript that supports arrow functions will also support ({[myKey]:myValue}), so this answer has no actual use-case (and, in fact, it might break in some bizarre corner-cases).
Don't use the below-listed method.
I can't believe this hasn't been posted yet: just use arrow functions with anonymous evaluation!
Completely non-invasive, doesn't mess with the namespace, and it takes just one line:
myNewObj = ((k,v)=>{o={};o[k]=v;return o;})(myKey,myValue);
demo:
var myKey="valueof_myKey";
var myValue="valueof_myValue";
var myNewObj = ((k,v)=>{o={};o[k]=v;return o;})(myKey,myValue);
console.log(myNewObj);
useful in environments that don't support the new {[myKey]: myValue} syntax yet, such as—apparently; I just verified it on my Web Developer Console—Firefox 72.0.1, released 2020-01-08. I stand corrected; just wrap the thing in parenthesis and it works.
(I'm sure you could potentially make some more powerful/extensible solutions or whatever involving clever use of reduce, but at that point you'd probably be better served by just breaking out the Object-creation into its own function instead of compulsively jamming it all inline)
not that it matters since OP asked this ten years ago, but for completeness' sake and to demonstrate how it is exactly the answer to the question as stated, I'll show this in the original context:
var thetop = 'top';
<something>.stop().animate(
((k,v)=>{o={};o[k]=v;return o;})(thetop,10), 10
);
Given code:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
Translation:
var thetop = 'top';
var config = { thetop : 10 }; // config.thetop = 10
<something>.stop().animate(config, 10);
As you can see, the { thetop : 10 } declaration doesn't make use of the variable thetop. Instead it creates an object with a key named thetop. If you want the key to be the value of the variable thetop, then you will have to use square brackets around thetop:
var thetop = 'top';
var config = { [thetop] : 10 }; // config.top = 10
<something>.stop().animate(config, 10);
The square bracket syntax has been introduced with ES6. In earlier versions of JavaScript, you would have to do the following:
var thetop = 'top';
var config = (
obj = {},
obj['' + thetop] = 10,
obj
); // config.top = 10
<something>.stop().animate(config, 10);
2020 update/example...
A more complex example, using brackets and literals...something you may have to do for example with vue/axios. Wrap the literal in the brackets, so
[ ` ... ` ]
{
[`filter[${query.key}]`]: query.value, // 'filter[foo]' : 'bar'
}
ES5 implementation to assign keys is below:
var obj = Object.create(null),
objArgs = (
(objArgs = {}),
(objArgs.someKey = {
value: 'someValue'
}), objArgs);
Object.defineProperties(obj, objArgs);
I've attached a snippet I used to convert to bare object.
var obj = {
'key1': 'value1',
'key2': 'value2',
'key3': [
'value3',
'value4',
],
'key4': {
'key5': 'value5'
}
}
var bareObj = function(obj) {
var objArgs,
bareObj = Object.create(null);
Object.entries(obj).forEach(function([key, value]) {
var objArgs = (
(objArgs = {}),
(objArgs[key] = {
value: value
}), objArgs);
Object.defineProperties(bareObj, objArgs);
});
return {
input: obj,
output: bareObj
};
}(obj);
if (!Object.entries) {
Object.entries = function(obj){
var arr = [];
Object.keys(obj).forEach(function(key){
arr.push([key, obj[key]]);
});
return arr;
}
}
console(bareObj);
If you want object key to be same as variable name, there's a short hand in ES 2015.
New notations in ECMAScript 2015
var thetop = 10;
var obj = { thetop };
console.log(obj.thetop); // print 10
You can do it this way:
var thetop = 'top';
<something>.stop().animate(
new function() {this[thetop] = 10;}, 10
);
This way also you can achieve desired output
var jsonobj={};
var count=0;
$(document).on('click','#btnadd', function() {
jsonobj[count]=new Array({ "1" : $("#txtone").val()},{ "2" : $("#txttwo").val()});
count++;
console.clear();
console.log(jsonobj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>value 1</span><input id="txtone" type="text"/>
<span>value 2</span><input id="txttwo" type="text"/>
<button id="btnadd">Add</button>
You could do the following for ES5:
var theTop = 'top'
<something>.stop().animate(
JSON.parse('{"' + theTop + '":' + JSON.stringify(10) + '}'), 10
)
Or extract to a function:
function newObj (key, value) {
return JSON.parse('{"' + key + '":' + JSON.stringify(value) + '}')
}
var theTop = 'top'
<something>.stop().animate(
newObj(theTop, 10), 10
)

Resources