Push to array in nested immutable object - immutable.js

Please i want to have object like below from none existing group object.
{
name: '',
group: {
[nameValue]: [1,2,3,4]
}
}
I want to push an item to the [nameValue] provided it match the text. My code below
myObj.mergeDeep(myObj , {
groups: {
[newObject.get('key')]: newObject
}
});
The code above update my [newObject.get('key')] as an object. My question is [newObject.get('key')] is of type array, how do i pls push to the array instead of object. I want to have an array of items under [newObject.get('key')] instead. Any help would be appreciated.

assuming myObj is an Immutable Map or similar, you can use .updateIn(). docs
myObj = myObj.updateIn(
[newObject.get('key')],
List(),
list => list.push(newObject)
);

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.

How to get object of object in JSON API response?

I'm using Ionic with Angular. I have a JSON API response and I want to get the items of an object inside an object, in this case, author items.
JSON API response
{
x{
**authors**:{
auth-sara-rts-2022:
Code: "rts"
Contact:{
email:"xx#gmail.com"
phone:"0.."}
[[Prototype]]: Object
auth-sami-sgs-2022:
Code: "sgs"
Contact:{
email:"xx#gmail.com"
phone:"0.."}
[[Prototype]]: Object
[[Prototype]]: Object
}
[[Prototype]]: Object},
y{
yy: "text"
[[Prototype]]: Object}
[[Prototype]]: Object}
}
Here is how to call the API in ts file
callAPI(body: any, header: any): Observable<any> {
return this.http.post(API_URL+API_ENDPOINT,body,header);
}
postAPI(body:any,header) {
this.callAPI(body, header).subscribe(
(data) => { console.log(data.x.authors);
}
);
}
I get a list of authors, and I'd like to access the items in each author's collection (code and contact).
I tried this code, but it returned an undefined value.
console.log(data.x.authors[0]);
The issue you're having is that you are trying to use Array notation (data.x.authors[0]) to access key/value pairs in an Object. In order to transform the authors Object into an Array, there are multiple approaches. I would propose Object.entries, which returns an Array of tuples, each tuple containing the key followed by the value:
const authors = Object.entries(data.x.authors);
console.log(authors[0]); // ['auth-sara-rts-2022', { Code: 'rts', ... }]
Here are the MDN docs for Object.entries():
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

How can I map JSON to object using enums for property names in Dart

I'm trying to map JSON data to an object using enums for property names. I currently receive object names in this format 'my.property.test' from the services. How can i use enums to map these names to my Object names?
{
‘my.propert1’: {
'subprop1':'val',
'subprop1':'val'
},
'my.propert2’: {
'subprop1':'val',
'subprop1':'val',
}
}
My enum example:
enum propertyNames {
my.propert1,
my.propert2
}
Object to map to:
class MyObject {
Property propert1,
Property propert2
}
Fyi, I'm a noob and still trying to understand JSON => object mappings, especially in Dart.
for parsing directly like in java ?? unfortunately no, but you can make a function like this to do it for you:-
ENUM mapAnEnum(String name) {
for (var item in ENUM.values) {
//addin toLowerCase() to just be sure but feel free to remove it !
if (item.toString().toLowerCase() == name.toLowerCase()) return item;
}
}

How to iterate a list inside of a JSON object using Kotlin

I am receiving a JSON object from an HTTP request using the Fuel library that looks like:
{
'items': ['item1', 'item2', 'item3']
}
My code for getting the JSONobject is:
Fuel.get("get_cameras").responseJson { request, response, result ->
var my_json = result.get().obj()
}
How can I iterate over the 'items' key? I have tried:
for (items in my_json) {}
but it says it doesn't have an iterator() method. I am coming from Python and am probably thinking about this in the wrong way because I see plenty of other seemingly similar questions but none seem to be related to what I am trying to do.
You need to first get a hold of the array nested in your object with the "items" key, and then you can iterate over that array. The basic way to do this (if you're sure that it only contains strings) would be to loop over its indexes and call getString on the array for each index:
val my_json = result.get().obj()
val items = my_json.getJSONArray("items")
for (i in 0 until items.length()) {
val item = items.getString(i)
// use item
}
If you don't want to deal with indexes while iterating, you could wrap the iteration of a JSONArray into an extension function:
fun JSONArray.forEachString(action: (String) -> Unit) {
for (i in 0 until length()) {
action(getString(i))
}
}
Which could then be used like this:
val items = my_json.getJSONArray("items")
items.forEachString { item ->
// use item
}
You could extend the JSONArray class with an iterator function as well if you really wanted to iterate the array with a regular for loop, but it would be more trouble than it's worth.

Json manipulation TypeScript Angular 2

I come from a Python Background and recently started programming using TypeScript and Angular2. I want to know how to obtain keys from a JSON object using TypeScript.
I have a response like so:
response.text()
I pass this object to a function
removeMetaData (my_data: string){
//(Various manipulation)...etc
}
i have read that I can call a json() method instead of text(). If I do that, what is the type I should use for my_data?
Then,
If my JSON looks like this:
{
"count": 100,
"next_page": "http://www.test.com/users/?page=2",
"prev_page": "http://www.test.com/users/?page=3",
"results":[
{
"username": "johnny"
},
Etc....
]
How do I parse that?
I've read I might have to use an interface but I don't understand how.
In python it's just response["next_page"] to get the key of a dictionary, then I can assign that value to a variable within the class. That is exactly what I'm trying to achieve within a component.
Thank you.
ADDITION
list() {
this.requestService.get(this.api_path)
.subscribe(
response => this.populate(response.json()),
error => this.response = error.text()
)
}
populate(payload: object) {
this.count = payload.count;
this.next = payload.next;
this.previous = payload.previous;
*payload.results => this.users = payload.results;******
}
Declare an interface which will be used as value object.
export interface IPage
{
count:number;
next_page:string;
prev_page:string;
results:Array<any>;
...
...
}
var my_data:IPage;
Now assign parsed json value to my_data and access all the properties with '.' operator i.e. my_data.count, my_data.results.
Feel free to throw any question.
If I do that, what is the type I should use for my_data?
Its just a javascript object.
As an example if you json looks like:
{
"foo": {
"bar": "bas"
}
}
Then in the parsed json (in variable someObj) the value someObj.foo.bar would be bas 🌹