How can I declare a two dimensional array in React? - reactjs

I try to do this:
getInitialState: function(){
return({
people: [] .... or people: [{id: "", key: ""}] or people: [[id: ][key: ]]
});
},
so I have an id and a key every person and I want to store it like this.

Looks like a syntax error. Try:
getInitialState () {
return {
people: []
};
}
This creates an empty array in your initial state. You can just populate your people array normally like so:
let p = this.state.people.slice();
p.push({id: "", key: ""});
this.setState({people: p});
The first line creates a copy of your people. You then push a new item to the temporary array. Finally you replace the old people state with the new one.
A one-liner way of doing this:
this.setState({people: this.state.people.concat([{id: "", key: ""}])});

Related

How to push array value with defined object in angular

My array
let myArr=["test1","test2"];
Need to add the object like below
let myFinalArr=[["test1":{"val1":"XXX","val2":"YYY"}],["test2":{"val1":"XXX","val2":"YYY"}]];
how to push the data like above in angular.
There are multiple ways to do it. How exactly does the requirement look? Does the object remain same for all the elements in the array?
And expanding from your comment that the following is the actual output's structure
{
"test1": { "val1":"XXX", "val2":"YYY" },
"test2": { "val1":"XXX", "val2":"YYY" }
}
You could try the Array#reduce with spread operator to transform the array
let myArr = ["test1", "test2"];
const output = myArr.reduce((acc, curr) => ({
...acc,
[curr]: { val1: "XXX", val2: "YYY" }
}), Object.create(null));
console.log(output);

Adding property in array. Add the last value in all array

"I'm adding a property on array while in a forEach loop. But when I do the console.log() the added value on each array is always the last value of the foreach loop."
deliveries data has location and I want to pass the location to pickupDetails.
deliveries: [{ //data of deliveries that I want to pass in pickupDetails
0: {Location: Korea},
1: {Location: Japan}
}]
let pickupDetails = this.state.pickupDetails;
//pickupDetails is only one object then It will become two since the deliveries has 2 objects
pickupDetails = {
name: "June"
}
this.state.deliveries.forEach((delivery, index) => {
pickupDetails.location = delivery.location;
console.log(pickupDetails)
})
the result of the console:
pickupDetails = {
name: "June"
location: "Japan" //this should be Korea since the first loop data is korea
}
pickupDetails = {
name: "June"
index: "Japan"
}
I think something missing from that code maybe because its dummy data. alright from my point of view you confused with javascript reference.
deliveries: [{ //data of deliveries that I want to pass in pickupDetails
0: {Location: Korea},
1: {Location: Japan}
}]
let pickupDetails = this.state.pickupDetails;
this.state.deliveries.forEach((delivery, index) => {
let newPickupDetails = JSON.parse(JSON.stringify(pickupDetails));
newPickupDetails.location = delivery.location;
console.log(newPickupDetails);
})
the result of the console:
pickupDetails = {
name: "Juan"
location: "Japan" //this should be Korea since the first loop data is korea
}
pickupDetails = {
name: "June"
index: "Japan"
}
JSON.parse and JSON.stringify we use for create new object instead of use reference. console log effected because it linked by reference so if you make it new object it will do.
Check variable newPickupDetails

How to save an empty array as property of a nested object in mongoose?

I have the following code:
var lesson = new Lesson({
classroomId: req.params.classroomId,
name: req.body.name,
startDate: startDate1,
endDate: endDate1,
teacher: {
_id: classroom.teacher._id,
attendance: [],
},
students: [],
});
lesson.save();
When I check in the backend, the teacher key just has the _id property and the attendance property wasnt saved. I suspect this is because it is an empty array. How can I save an empty array like this?
It may be because Lesson Schema is not defined properly. Did you try setting...
mongoose.Schema({
.....
teacher: {
...
attendance: { type: Array, default: [] }
}
...
});

Update a nested value in a store

I have my state with the following structure:
{ messages:
[
{ id: 1, comments: []}
]
}
And I would like to add a new comment in my message, I have the message id so I can easily create a new state, loop over the messages, and add the new comment, but it doesn't seem to be the right way...
Thank you for your help.
Try this:
var commentToAdd = { id: 1, comment: "text" };
this.setState({ messages: [...this.state.messages.map(i => i.id === commentToAdd.id ? { id: i.id, comments: [...i.comments, commentToAdd.comment] } : i) ] });
The best practice is to keep state in the normalized shape, so instead of arrays, you would have objects indexed by id, and instead of storing comments inside messages you would store only ids.
For your example the state would look like this:
{
messages: {
byId: {
'1': { id: '1', comments: ['comment1'] },
...
},
allIds: ['1', ...]
},
comments: {
byId: {
'comment1': { id: 'comment1', ... },
...
},
allIds: ['comment1', ...]
}
}
In such structure in order to add a new comment you will have to update comments part and add a new id in messages[id].comments... but it's now much easier to update single comment.
For normalizing objects to such form I recommend normalizr.
More information about normalizing state shape in redux documentation Normalizing State Shape

Sorting a nested array from model in Ember?

So I have a model in Ember that is generating a hash with three objects. One of the objects is an array of objects with another array inside each object. I need to sort this innermost array, but I am having trouble doing so.
Here are my models.
App.Person = DS.Model.extend ({
first_name: DS.attr('string'),
last_name: DS.attr('string'),
age: DS.attr('string'),
gender: DS.attr('string'),
innerMostArray: DS.hasMany('innerMostObject')
});
App.innerMostObject = DS.Model.extend ({
person_id: DS.belongsTo('person'),
attr1: DS.attr('string'),
attr2: DS.attr('string')
});
Here is my Route
App.NestedArrayRoute = Ember.Route.extend({
model: function(params) {
return Ember.RSVP.hash({
object1: this.store.find('object1', params.object1_id),
people: this.store.all('person'),
object3: this.store.all('object3')
});
},
afterModel: function(model, transition) {
model.people.forEach(function(item, index, enumerable){
var innerMostArray = item.get('innerMostArray');
var sortedArray = innerMostArray.sortBy('attr1', 'attr2');
});
model.people.update();
}
});
I know that I am nowhere near doing this right but I just don't know how to sort this nested array. I've seen examples of array controllers, but I don't know how to use one to sort this nested array. If anyone could give an example of how to do this it would be very helpful. Thank you.
I agree with Kalmans answer, but I suggest you do this sorting with built-in methods to save you trouble:
App.Person = DS.Model.extend({
name: DS.attr('string'),
fruits: DS.hasMany('fruit', {async: true}),
fruitSorting: ['title', 'color'],
sortedFruits: Ember.computed.sort('fruits', 'fruitSorting')
});
I forked his example here: http://emberjs.jsbin.com/manutu/1/edit?html,js,output
One way to do this is to create a computed property on the model as follows:
App.Person = DS.Model.extend({
name: DS.attr('string'),
fruits: DS.hasMany('fruit', { async: true }),
sortedFruits: function(){
var fruits = this.get('fruits');
return fruits.sortBy('title', 'color');
}.property('fruits.#each.title', 'fruits.#each.color')
});
Working example here

Resources