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.
Related
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?
I have a function to denormalize json data.
Json data looks like:
-entries
- entry
- skus
What I am trying to do is to create an array of objects where entries with more than 1 SKUs should be repeated the x times, where x is the number of skus (length of the sku array); each time switching the data of the skus.
The problem is that the sku data does not switch, and the same skus are shown multiple times in the resulting array.
When I debug step by step, the array is appended fine at the beginning, however when function proceeds the correctly appended elements of the array are overwritten.
Here the function code:
let data = [
{
name: 'a',
skus: [1, 2],
},
{
name: 'b',
skus: [3, 4],
},
{ name: 'c', skus: [5] },
{ name: 'd', skus: [6, 7, 8] },
];
function flatten(data) {
let newArray = [];
for (i in data) {
const el = {};
el.name = data[i].name;
let skus = data[i].skus;
for (j in skus) {
el.sku = skus[j];
newArray.push(el);
console.log(el);
}
}
return newArray;
}
what I am trying to achieve is to return a new array which is so:
[
{ name: a,
sku: 1
},
{ name: a,
sku: 2
},
{
name: b,
sku: 3,
},
{
name: b,
sku: 4,
}... and so on ]
Thanks
You want to achieve the following conversion.
From
const data = [
{name: 'a', skus: [1, 2]},
{name: 'b', skus: [3, 4]},
{name: 'c', skus: [5]},
{name: 'd', skus: [6, 7, 8]},
];
To
[
{"name": "a", "sku": 1},
{"name": "a", "sku": 2},
{"name": "b", "sku": 3},
{"name": "b", "sku": 4},
,
,
,
]
Modification points:
I think that the reason of your issue is due to the call by reference. When the object el is put to the array with newArray.push(el), el is changed by the next loop. By this, I think that your issue occurs. In this case, it is required to copy the object and put to the array.
When above points are reflected to your script, it becomes as follows.
Modified script:
From:
newArray.push(el);
To:
newArray.push(Object.assign({}, el));
Testing:
let data = [
{name: 'a', skus: [1, 2]},
{name: 'b', skus: [3, 4]},
{name: 'c', skus: [5]},
{name: 'd', skus: [6, 7, 8]},
];
function flatten(data) {
let newArray = [];
for (i in data) {
const el = {};
el.name = data[i].name;
let skus = data[i].skus;
for (j in skus) {
el.sku = skus[j];
newArray.push(Object.assign({}, el));
// console.log(el);
}
}
return newArray;
}
console.log(flatten(data))
Other pattern:
In your case, the following script can be also used.
const data = [
{name: 'a', skus: [1, 2]},
{name: 'b', skus: [3, 4]},
{name: 'c', skus: [5]},
{name: 'd', skus: [6, 7, 8]},
];
const res = data.reduce((ar, {name, skus}) => {
skus.forEach(e => ar.push({name: name, sku: e}));
return ar;
}, []);
console.log(res);
Reference:
Object.assign()
I am attempting to pull data out of json like this, which is imported as "values"
{
"content": {
"person": [
{
"name": "Test"
"age" : "24:
}
]
}
}
I am using .map like below but getting the error .default.map is not a function I believe it is because i have objects not arrays, i've tried a bunch of stuff including object.keys but i'm getting errors all over the place, any direction would be appreciated.
import values from './sample.json'
const vals = values.map((myval, index) => {
const items = person.items.map((item, i) => {
return (
<div>{item.name}</div>
)
})
return (
<div>{items}</div>
)
})
I think your data and code have some errors. But after fixing those and also changing the name from 'person' to 'people' if that's what you are after, here's the code that does what you are trying to do:
var data = {
content: {
people: [
{
name: "Test",
age: 24,
},
{
name: "Foo",
age: 25,
},
],
},
};
var App = React.createClass({
render: function () {
var people = data.content.people.map(function (person) {
return <div>{person.name}</div>;
});
return <div>{people}</div>;
},
});
ReactDOM.render(<App />, document.getElementById("app"));
And here's the JSBin for that: https://jsbin.com/coyalec/2/edit?html,js,output
Update: I'm updating the answer with more detailed example. It now deals with data more generically, like it doesn't assume what are the entries of 'contents' and such, but it knows that each type like 'people' or 'pets' are an array.
var data = {
content: {
people: [
{
name: "Test",
age: 24,
},
{
name: "Foo",
age: 25,
},
],
pets: [
{
name: "Sweety",
age: 3,
},
{
name: "Kitty",
age: 5,
},
],
},
};
var App = React.createClass({
render: function () {
// Get the keys in data.content. This will return ['people', 'pets']
var contentKeys = Object.keys(data.content);
// Now start iterating through these keys and use those keys to
// retrieve the underlying arrays and then extract the name field
var allNames = contentKeys.map((t) =>
data.content[t].map((e) => <div>{e.name}</div>)
);
return <div>{allNames}</div>;
},
});
ReactDOM.render(<App />, document.getElementById("app"));
And here's the latest JSBin: https://jsbin.com/coyalec/4/edit?html,js,output
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
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" }
};