What are alternetives to Object destructuring in Dart? - json

If you had a JSON-encoded response ...
You can print a list of records in javascript like this...
const doc = {
record: [
{id: 3},
{id: 5},
],
metadata: {
id: "test",
},
};
//The destructuring assignment also works with objects in javascript
const {
record: r,
metadata: m
} = doc;
const list = r.map(rec => rec.id);
console.log(list);
How do I split a JSON object then create a list of values using Dart?

Related

jQuery array to splited json

Hello I have am trying to build a post request. Below is the format that I have to send
const data = {
categories: [
{
id: 9
},
{
id: 14
}
],
}
But what I have is ["29", "23", "22"] : these are category ids
Please help
You can use .map:
const arr = ["29", "23", "22"];
const data = {
categories: arr.map( e => ({ id: e }) )
};
console.log(data);

Why .push() replacing the last object of JSON array?

I have developed an Angular4 basic CRUD application that interacts with a nodejs backend API that renders data of a JSON array. But on adding an object to the JSON array using .push() method it replaces the last object with the new to be added object instead of pushing it to the array.
The following is the definition of Employee :
export interface Employee {
id:number,
name:string,
review:string[],
peers:string[]
}
The service method makes the HTTP call is following:
addEmployee(addedEmployee:Employee):Observable<Response>
{
return
this._http.post("http://localhost:3001/add",addedEmployee)
.pipe(catchError(this.handleError));
}
The backend API code that adds an Employee object to JSON object array is following:
app.post('/add',function(req,res){
var addedEmployee={};
addedEmployee.id=req.body.id;
addedEmployee.name=req.body.name;
addedEmployee.review=req.body.review;
addedEmployee.peers=req.body.peers;
employees.push(addedEmployee);
console.log('added');
res.json(employees);
})
The before, intermediate and after structures of the backend JSON object array are following:
Before:
employees = [
{
id: 1,
name: "John Doe",
review: ["Hardworking"],
peers: ["admin", "Matt"]
},
{
id: 2,
name: "Matt Hofner",
review: ["Hardworking"],
peers: ["admin"]
},
{
id: 3,
name: "Judy Ruth",
review: ["Focused"],
peers: ["admin", "Matt"]
}
];
Intermediate:
let addedEmployee:Employee = {
id: 4,
name: "Trudy",
review:["Lazy"],
peers: ["Matt"]
};
Final :
employees = [
{
id: 1,
name: "John Doe",
review: ["Hardworking"],
peers: ["admin", "Matt"]
},
{
id: 2,
name: "Matt Hofner",
review: ["Hardworking"],
peers: ["admin"]
},
{
id: 4,
name: "Trudy",
review: ["Lazy"],
peers: ["Matt"]
}
];
That's odd. This might not be the best solution but try the .concat() method :
app.post('/add',function(req,res){
var addedEmployee={};
var singleEmployeeArray = [];
addedEmployee.id=req.body.id;
addedEmployee.name=req.body.name;
addedEmployee.review=req.body.review;
addedEmployee.peers=req.body.peers;
singleEmployeeArray.push(addedEmployee);
employees.concat(singleNewEmployeeArray);
console.log('added');
res.json(employees);
})

Adding single element to an immutable list

i want to just add an element to a list somewhere in my immutable object tree.
This question appears to have been answered here :
Append value to List
But for some reason it does not work for me.
If I have the following code :
var myState = {
a: {
b: {
c: [
{name: 'hi', value: 2},
{name: 'howdy', value: 3}
]
}
}
}
myState = Immutable.fromJS(myState);
myState = myState.update(['a', 'b', 'c'], function (myList) {
myList.push({"name": "hallo", "value": 4})
}
);
I get an error :
Uncaught TypeError: Cannot read property 'push' of undefined
which indicates that the myList parameter being passed into the callback is null.
Why is this happening?
fiddle:
https://codepen.io/owatkins/pen/brMava
This is how it should be written:
myState.updateIn(['a', 'b', 'c'], function (myList) {
return myList.push({"name": "hallo", "value": 4})
}
);
Below is a working example:
var myState = Immutable.fromJS({
a: {
b: {
c: [{
name: 'hi',
value: 2
},
{
name: 'howdy',
value: 3
}
]
}
}
})
myState = myState.updateIn(['a', 'b', 'c'], function(myList) {
return myList.push({
"name": "hallo",
"value": 4
})
});
console.info('myState = ' + myState.toJS())
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.min.js"></script>
notice that I'm using updateIn instead of update and returning the result of push
After much stuffing around, the only solution I could come up with is to get the array, and convert to JS, push an element onto it, then convert it back to an immutable... and then use setIn, NOT updateIn, and NOT update.
var myState = {
a: {
b: {
c: [
{name: 'hi', value: 2},
{name: 'howdy', value: 3}
]
}
}
}
myState = Immutable.fromJS(myState);
var list = myState.getIn(['a', 'b', 'c'])
var list = list.toJS();
list.push({"name": "hallo", "value": 4});
var v = Immutable.fromJS(list)
myState = myState.setIn(['a', 'b', 'c'], v)
This looks like a horrible solution, but it is the only thing that works for me so far.
Usually it takes about 5 minutes to learn how to add an element to a list in a framework or language.
I wasn't expecting it to take 5 HOURS.
The documentation for this framework is an absolute disgrace.

Get Array Of Object On ajax Call success

I will make Ajax call on my Controller action method. I want result of JSON in this format.
// array of all brands
var brands = [
{ brandId: 1, name: "Ford" },
{ brandId: 2, name: "BMW" }
];
for this i will make another call
// array of all models
var models = [
{ modelId: 1, name: "Explorer", brandId: 1},
{ modelId: 2, name: "Focus", brandId: 1},
{ modelId: 3, name: "X3", brandId: 2},
{ modelId: 4, name: "X5", brandId: 2}
];
How can i do that please guide me.
You can use following code to solve your problem
public ActionResult SomeActionMethod(int id)
{
return Json(new {foo="bar", baz="Blech"});
}
Method from the jquery getJSON method by simply...
$.getJSON("../SomeActionMethod", { id: someId },
function(data) {
alert(data.foo);
alert(data.baz);
}
);
To serialize json in your controller, may be you can use http://www.newtonsoft.com/json/help/html/serializingjson.htm

ImmutableJS: Convert List to indexed Map

This question is about Immutable.js library.
I have a List<T>, where T is {name: string, id: number}. I want to convert it to Map<number, T>, with id of T to the keys. Using standard method toMap gives me a Map with sequential indexes, and there is no way to hook there. And no method like indexBy or other. how to do that?
You can do it with a reducer like this:
function indexBy(iterable, searchKey) {
return iterable.reduce(
(lookup, item) => lookup.set(item.get(searchKey), item),
Immutable.Map()
);
}
var things = Immutable.fromJS([
{id: 'id-1', lol: 'abc'},
{id: 'id-2', lol: 'def'},
{id: 'id-3', lol: 'jkl'}
]);
var thingsLookup = indexBy(things, 'id');
thingsLookup.toJS() === {
"id-1": { "id": "id-1", "lol": "abc" },
"id-2": { "id": "id-2", "lol": "def" },
"id-3": { "id": "id-3", "lol": "jkl" }
};