Iterate over array in proxy [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 months ago.
Improve this question
Good day.
I was testing stuff in Javascript with Proxies.
Currently I have this proxy
My question was, how do I iterate over this? I've tried several methods, including object.keys and forEach, which yielded nothing.
Thanks in advance

You need to specify an ownKeys method in the handler you're using to create the proxy or you won't be able to enumerate the keys of the proxy object.
const obj = { test: 'a' };
const handler1 = {
ownKeys(target) {
return Reflect.ownKeys(target);
}
};
const proxy1 = new Proxy(obj, handler1);
console.log(Object.keys(proxy1)) // ['test']
Edit
Actually, you can use Reflect.ownKeys directly also, but you'll want to make sure the behavior is what you expect. For example, it might return length as a key as well.

Related

JSON structure in javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 days ago.
Improve this question
I am trying to create a javascript structure that looks like that:
[{'red': {color:'red},...}]
starting with an array of colors:
const COLORS = ['red','yellow']
This is what I have tried:
const finalArray = COLORS.map(color => ({ [color]: { color } }))
However this produces an array that looks like that:
[{red: {color:'red'}}]
instead of [{'red': {color:'red'}}]
Which is not the same and will prevent the library I am using from understanding the array.
Any idea is welcome.
I edited the question since there where some typos. Hope it’s clearer now.
Thanks
What are the differences between:
[{red: {color:'red'}}]
// and
[{'red': {color:'red'}}]
If it's only a quote related matters, you can do like:
COLORS.map(color => ({ [`'${color}'`]: { color } }));
These are just two ways of representing the same array/object. If you need a string containing the canonical representation of the array/object (with double quotes around the names of the properties), you can use JSON.stringify(finalArray).
Please note this will quote ALL your property names, like in:
[{"red":{"color":"red"}}]
And please note the above is a string, as if you did:
finalString = '[{"red":{"color":"red"}}]'
(Note: this question has been closed, and I agree it's not clear enough. But it's quite evident that the user is confusing the internal structure of an array/object with its external representation, and with the way the array/object is shown by a development environment, browser, etc. As this is a very common problem, mostly in new programmers or newcomers to a tool, the question and the answers may still be helpful.)

How to use "this" with object spread to set class properties [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 months ago.
Improve this question
Can i do this in one line without the intermitten variables.
const { state$, toggleState } = StateManagement.useToggleState$(initialState);
this.layoutState$ = state$;
this.toggleState = toggleState;
Something like this
{ state$: this.layoutState$, toggleState: this.toggleState } = StateManagement.useToggleState$(initialState);
When I wrap it in paranthesis like below, the IDE stops throwing errors, but they are not actually assigned.
({ state$: this.layoutState$, toggleState: this.toggleState } = StateManagement.useToggleState$(initialState));
Apparently my problem came from typescript not doing its thing when you assign a declared property in the constructor (Inferring its type). So, I just needed to manually write its type in the declaration.
toggleLayoutState: (key: keyof LayoutState) => void;
constructor() {
({ state$: this.layoutState$, toggleState: this.toggleLayoutState } = StateManagement.useToggleState$(initialState));
}
Normally it should understand the type, even if you don't explicitly state it. Something to fix by typescript contributors maybe, or I am missing something.
PS: Not deleting the question, since it would have helped me if it existed before. Mods can delete it If I am breaking any rules I guess.

Promise all convention approaches [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
we did some code review and it the code before was like following:
run: () =>{
var _this = this;
return Promise.all([
//Get command
cp.getCommand(constants.HB),
//Find port
cp.findPort()
]).spread((r1, r2) => {
...
After the code review my colleagues suggest to change it to the following which I disagree
since you need to add unnecessary code (the array & push) and Im not sure that this is more readable, what do you think?
run: function () => {
var _this = this;
var promiseArray = [];
//Get command
promiseArray.push(cp.getCommand(constants.HB));
//Find port
promiseArray.push(cp.findPort());
return Promise.all(promiseArray)
.spread((r1, r2) => {
There is no particular reason to put the promises into an explicitly declared array before passing them to Promise.all() so it's pretty hard to defend that the second option is "better" than the first option.
In fact, you could easily make a case that the second option just creates an unnecessary named variable containing the intermediate array and does unnecessary .push() function calls.
In the end, there is no absolute right or wrong here. This is merely a matter of opinion on coding style. Code reviews are often part defensible logic and part reviewer's opinion. It appears you just ran into some opinion where the reviewer has a different opinion than you do.
If you want to push back on a review issue like this, then you should ask them to defend why they their method is necessarily better than your first approach.

Array[key].push Is Not Defined in JavaScript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
When trying to push items to an array in javascripts it gives an error, the following pseudo code illustrate what is happening:
var data = new Array();
for(...) {
data[key].push(item[i]);
}
It is showing the following error:
Cannot read property 'push' of undefined
Thanks
If you need a 2d array, you have to initialize each element of the outer array to be an array.
// Have to check every array item, if it's not an array already, make it so
for(...) {
if (!data[key]) {
data[key] = [];
}
data[key].push(item[i]);
}
You could always do the following if you know the number of inner arrays you need:
var data = [[],[],[],[],[],[]];
In your example, since they variable name is key, I'm assuming you actually want an object of arrays. If you know the keys ahead of time, you can use the following literal.
var data = {
myKey1: [],
myKey2: []
}

To understand monkey patching in Javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to understand the concept behind how monkey-patch works in JavaScript?
I've gone through too many examples but couldn't able to understand
For example - Monkey patching the dispatch function in Redux
let next = store.dispatch
store.dispatch = function dispatchAndLog(action) {
console.log('dispatching', action)
let result = next(action)
console.log('next state', store.getState())
return result
}
Source: http://redux.js.org/docs/advanced/Middleware.html#attempt-3-monkeypatching-dispatch
Can anyone please explain monkey patching in simple terms and example
And which is the best scenarios to use it?
Thanks.
Let say you use a library which define a class Test with a method test.
If you want to monkey patching-it you have to use this kind of code and include it after the library :
// replacing current implementation with a new one
Test.prototype.test = function(arg1, arg2, ...){...}
Now let say you want to do something a bit smarter, like adding something to the function without modifying the rest here is how you would do it :
var oldFN = Test.prototype.test;
Test.prototype.test = function([arguments...]){
[...some custom code...]
oldFN.apply(this, arguments);// arguments keyword refer to the list of argument that your function recevied, if you need something else use call.
[...some custom code...]
}
Monkey patching is valid but must be used wisely. Furthermore each time you upgrade the library, you must check that all your patches works still fine.

Categories

Resources