Delete Multiple Object Properties Using Destructuring - ecmascript-6

I am trying to delete multiple computed properties from an object at once using destructuring. Something like this
const a = {b: 1, c: 2 , d: 3};
const forbiddenKeys = [ "b", "c"]; // pretend this is computed
const { ...forbiddenKeys, ...rest } = a; // gives "Uncaught SyntaxError: Rest element must be last element"
My plan was to use the rest variable after these operations to get the rest of the object that is not contained in forbiddenKeys. Is there a way to do this so that it works like the "Rest in object destructuring" section here? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Computed_object_property_names_and_destructuring

Related

Google Apps Script: How to get values from all dynamic keys in deeply nested object

Trying to retrieve all the dividend values from the object in this url. I'm getting an error, "TypeError: obj.chart.result[0].events.dividends.map is not a function". I'm trying to build a basic coding skill in handling nested objects. What should be changed in this code? Some explanation would be greatly helpful. Thank you!
function test() {
var url = "https://query1.finance.yahoo.com/v8/finance/chart/VZ?formatted=true&lang=en-US&region=US&interval=1d&period1=1451624400&period2=1672963200&events=div&useYfid=true&corsDomain=finance.yahoo.com";
var obj = UrlFetchApp.fetch(url, { muteHttpExceptions: true }).getContentText();
var obj = JSON.parse(obj);
var dividend = obj.chart.result[0].events.dividends.map(o => (({ o: { amount } }) => amount));
console.log(dividend)
}
Your dividends is not an array. It's an object. In the programming space people might call it a hashmap, key-value pair, or map. Since this is JavaScript, might also consider it just JSON.
The way you're trying to use it though, using .map() is a method on arrays which is completely different from what object is--although an object might be referred to as a map.
The .map() array method is a for loop that takes a predicate to alter the elements of the array. For example,
[1,2,3,4,5].map((n) => {return n * 2})
// returns: [2,4,6,8,10]
Since dividends is some object like...
{
12345: {amount: 1, date: 12345678},
12346: {amount: 1, date: 12345678},
// etc
}
Then you might do something like...
Object.keys(obj.chart.result[0].events.dividends).map((dividend_id) => {
Logger.log(obj.chart.result[0].events.dividends[dividend_id])
})
In this example we put the dividends object into Object.keys() which would give back the ids of those dividends like [12345, 12346, 12347, ...].
In the .map() predicate, (dividend_id) => { /** do stuff like console.log */} we're taking that id and using it to open it's matching key and return the value of that key from dividends.

Why is The Parameter of a Function Retrieved From an Object "never"

I'd expect this code to work. But instead I get this TypeError.
The idea is that myFunctions holds handlers for data received from JSON.
The JSON objects are either of type A, or of type B. If type is "a" I want param to be handled by the function stored in myFunctions.
This is my approach, but the signature of the retrieved function is never allthough all type information is available.
const myFunctions = {
"a": function(o: string) {return "A"},
"b": function(o: number) {return "B"}
};
interface A {
type: "a"
param: string
}
interface B {
type: "b"
param: number
}
function getIt(i: A | B) {
const p = i.param;
const f = myFunctions[i.type];
// at this point typescript identifies the type of f to be ((o: string) => string) | ((o: number) => string)
return f(p); // <- Argument of type 'string | number' is not assignable to parameter of type 'never'. Type 'string' is not assignable to type 'never'.ts(2345)
}
Can someone explain to me why this behaviour occurs and how to fix it?
Alternatively I'd be happy to hear about other approaches to call the correct handler given a certain JSON object.
It is not possible to do this without introducing new if or switch statements. Typescript can't really follow that f and p are related and consistent with one another. Your use case could probably be helped by something like this proposal but that has been sitting as a proposal for a while so I would not really wait for it.
The issue here is that i.type is "A" | "B", so when using it to index myFunctions you just get back a union of all functions (((o: string) => string) | ((o: number) => string)). But this union of functions is only callable with an argument that is an intersection of all possible arguments. That intersection here is string & number which typescript reduces to never since it is a primitive intersection that can never be inhabited by any value. You can read here about the rules on union invocation.
You can add an if or switch to fix this, although it does make the code redundant:
function getIt(i: A | B) {
switch (i.type) {
case "a": return myFunctions[i.type](i.param)
case "b": return myFunctions[i.type](i.param)
}
}
Playground Link
Or use a type assertion to just make things work:
function getIt(i: A | B) {
const p = i.param;
const f = myFunctions[i.type];
return f(p as never);
}
Playground Link

How to find an element inside a json response and then set a variable based on another element's content inside that object?

This should be simple.
I am getting a json response in POSTMAN and need to search through it, and if I find an name in there, set an variable based on the id # of the object that contained that name :)
{ "jsonrpc": "2.0","result":[{"id": 396,"name": "LAB",},{ "id": 404,"name":"Networks",}],"id": 1}
etc...
So, if I need to find out the id of LAB, how to go about it?
Here we go:
its simple: iterate the json object and check if name is lab then print id
var x = { "jsonrpc": "2.0","result":[{"id": 396,"name": "LAB",},{ "id": 404,"name":"Networks",}],"id": 1}
x.result.forEach(function(value, index){
if(value["name"] == "LAB"){
console.log(value["id"]);
}
})
result is:
396

Create a record set based on an immutable object

I am receiving JSON data from an endpoint using Ajax.
const jsData = '[ {"x": 1, "y": 1}, {"x": 2, "y": 2}, … ]';
I am converting the data to an immutable object:
const imData = Immutable.fromJSON( jsData )
I want to create a record set base on this immutable object
const Rec = Immutable.Record( imData)
const rec = new Rec();
This error is thrown Uncaught TypeError: Cannot read property 'get' of undefined.
NOTE: Why am I not directly passing the jsData to be the default values of the record set ?
I don't want this to be possible: rec[0].x = 1.
What would be the correct way to convert the received data to a record set that is completely immutable ?
Your JSON data sample is invalid JSON.
You are not posting code sample which produces the error. Message says
Cannot read property 'get' of undefined. while in your samples you don't call get on anything.
Use objects to create Record. https://facebook.github.io/immutable-js/docs/#/Record
A record is similar to a JS object, but enforces a specific set of
allowed string keys, and has default values.
const jsData = '[{"x":1,"y":1},{"x":2,"y":2}]';
const imData = JSON.parse(jsData)
console.log(imData)
const Rec = Immutable.Record( imData[0])
const rec = new Rec();
console.log(rec.get('x'));
https://jsfiddle.net/sh637wsm/

How to loop and get the json object

{
"result": [
{
"id": "a258377906705d889422fd0b41c324b8",
"coordinate": {
"London": {
"x": 65.565709,
"y": 98.931235
},
"New_York": {
"x": 37.59751,
"y": 47.448718
}
}
}
]
}
If I have a json like the above one,
how can I loop to get the x,y coordinate and if i get more data to get, how can I get it?
If I want to also get the London and New York to add to an array list, how can I do it (cannot directly add the name because there are more than two data)?
You can parse it and then use it using JSON.parse( insert json here ).
Basically what it does is that it takes your JSON string and converts it into a usable JSON.
For adding new objects into another object, I recommend using Object.assign().
You can refer the details here: Link
Here is an example given from the site:
var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };
var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.
Object.assign() takes a target object as the first parameter and modifies it with the additional parameters that we're provided.
In your case, you can update your object like this:
var countryCoord = JSON.parse(yourjsondata); // parse the json that you included
Object.assign(countryCoord, newCoord, newCoord2,...etc); //this would update countryCoord alone
Online parser: Link
You have to handle the json and understand where you are getting the JSONObject and where you are getting the JSONArray, On basis of that you can parse the JSON accordingly.
Please refer the link for more information on parsing json object with nested items in Java:
Retrieving nested arrays values with java