JSON Object key value pair function [duplicate] - javascript

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 }

Related

How to get value from object using string of object path in typescript without using eval? [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 29 days ago.
In JS/typescript, lets say I have an object like this
var obj = {
a: {
b:{
c:1
}
}
}
And I have a string "b.c". How can I evaluate this using only those variables and get the value 1 from the object without using hacks like eval since typescript would complain.
Thanks
It I understood you question, the keys are known, if so you can use the '[]' to access it :
const a = b.c
is the same thing as
const a = b['c']
but in the second case you can of course use a variable.
Applying this to your object, it would look something like this :
const obj = {
a: {
b: {
c: 1
}
}
}
const outerKey = 'a'
const middleKey = 'b'
const innerKey = 'c'
const value = obj[outerKey][middleKey][innerKey]
console.log(value)
Hope it helped you !

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.

Using an empty object as a parameter to a conditional if loop [duplicate]

This question already has answers here:
How do I test for an empty JavaScript object?
(48 answers)
Closed 5 years ago.
This is similar to what I have been trying to do,
var obj = {};
if(obj){
//do something
}
What i want to do is that the condition should fail when the object is empty.
I tried using JSON.stringify(obj) but it still has curly braces('{}') within it.
You could use Object.keys and check the length of the array of the own keys.
function go(o) {
if (Object.keys(o).length) {
console.log(o.foo);
}
}
var obj = {};
go(obj);
obj.foo = 'bar';
go(obj);
You can check if the object is empty, i.e. it has no properties, using
Object.keys(obj).length === 0
Object.keys() returns all properties of the object in an array.
If the array is empty (.length === 0) it means the object is empty.
You can use Object.keys(myObj).length to find out the length of object to find if the object is empty.
working example
var myObj = {};
if(Object.keys(myObj).length>0){
// will not be called
console.log("hello");
}
myObj.test = 'test';
if(Object.keys(myObj).length>0){
console.log("will be called");
}
See details of Object.keys

Cannot understand object with array as key [duplicate]

This question already has answers here:
Difference between ES6 object method assignment: a, 'a', and ['a']?
(2 answers)
Closed 6 years ago.
I've found some wild code on the web i don't understand:
return Object.assign({}, state, {
[action.subreddit]: posts(state[action.subreddit], action)
})
What is [action.subreddit] doing? I thought that object keys had to be strings but this appears to be an array?
I'm hoping to understand mechanically how this code works.
thank you!
That's not an array as key, it's the es6 way to use a variable (/ a computed property) as the key.
Consider this:
var a = "foo";
function getKey() {
return "myKey";
}
var obj = {
[a] : "bar",
[getKey()] : "baz"
};
console.log(obj.foo); // bar
console.log(obj.myKey) // baz
So [action.subreddit] just sets the key's name to whatever value action.subreddit is holding.

Creating an 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)
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
}

Categories

Resources