Cannot understand object with array as key [duplicate] - javascript

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.

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 !

How to compare if second object has some value in first object then return true? [duplicate]

This question already has answers here:
How to determine equality for two JavaScript objects?
(82 answers)
Object comparison in JavaScript [duplicate]
(10 answers)
Closed last year.
I want to compare two objects as below:
First object:
const permissions = {
"statistics":{"list":"1"},"audit":{"list":"1"}}
}
Second object:
const userPermission =
{
"audit":{"list":"1"}
}
So, if the second object has some value the same as the first object then return true.
In this sample I want it return true. Becuase, audit has same properties.
var obj1 = {
name:'hello',
age:12,
fav: 'fav',
foo: 'foo'
}
var obj2 = {
name: 'hey',
say: 'say',
prop: 'prop',
top: 'top'
}
var common = Object.keys(obj1).filter(obj1item => Object.keys(obj2).indexOf(obj1item) !== -1 );
console.log(common);
You can look into this > Is there a way to check and see if two objects have properties in common?

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 }

Why does modifying values of let x = arr.filter(...) alter the values of arr? [duplicate]

This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 4 years ago.
I am struggling to understand the behavior of the following lines of code:
// I'd like to keep this value constant
let allObjects = [{value: null}, {value: 'Hello World'}]
// Here is a shorter list of objects matching some criteria
let someObjects = allObjects.filter(object => object.value)
// Here we work with the the values for some of the objects
someObjects[0].value = {hmm: 'test'}
// Kind of expecting allObjects[1].value to be 'Hello World' at this point
// Display all the objects
console.log(allObjects)
And the output:
[
{
"value": null
},
{
"value": {
"hmm": "test"
}
}
]
Here is a codepen.
What I do not understand is when the value of someObjects is modified it affects the value of allObjects and expect that allObjects[1].value will return Hello World.
Could someone explain to me why this is actually happening and how we are supposed create a sorter version of the array that does not mutate the original array when it is modified?
In JavaScript all primitive variables are passed by value however all objects are passed by a copy of its reference More Info. In your case, the array contains objects. Each index in the array contains a simple pointer to the memory location of an object. When you filter the array you are creating a new array with fewer values however the pointers are still pointing to the same internal objects. The filtered array, someObjects, contains a single pointer that points to the object { value: 'Hello World' }. You are overwriting the value property of this object with another object, { hmm: 'test' }. If you instead wanted to replace the object in the new filtered array rather than changing the value property of the old object you would do someObjects[0] = { hmm: 'test' }
const obj = { foo: 'bar' };
const copy = obj;
console.log(obj);
copy.foo = 'changed';
console.log(obj);

Can't use a string in an object path [duplicate]

This question already has answers here:
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Closed 5 years ago.
I have this code :
success(JSON.parse(xhr.responseText).items[0].snippet.title);
The problem is I can access what I want with this but I'd like to be able to do this :
var path = 'items[0].snippet.title';
success(JSON.parse(xhr.responseText).path);
And it doesn't work :(
It's probably nothing but I can't figure out why.
Thanks!
For accessing object properties by string you need to use [ ] notation:
var foo = {bar : 2};
foo['bar']; // 2
But that won't work for nested properties, here is the approach I would follow using Array.reduce and ES6:
let path = 'items.snippet.title';
let response = JSON.parse(xhr.responseText);
let result = path.split('.').reduce((pre,cur) => {
return pre[cur];
}, response);
success(result);
In the first iterarion pre will be response, and cur 'items' returning result.items and so on, it won't work when accesing array indexes though so you will need to add some extra logic inside the reduce function.
const [, cur, position] = cur.match(/^([^\[]+)(?:\[(\d+)])?$/);
// filter foo[1] capturing foo and 1, then assign them using destructuring.
// Thanks for edit!
return ( Array.isArray(pre[cur]) ? pre[cur][position] : pre[cur]);

Categories

Resources