{
id: "a",
deck_list: [{
name: 'Deck1',
job: 'mage',
cards: []
}],
match: []
}
Hi I am trying to make a DB for card game Decks. In 'deck_list', there are list of decks that created by users. Whenever user adds a new deck, then it would be inserted into deck_list.
However, when the name of the deck is already there, then the deck should be updated, rather than inserted.
Ex. If some deck named 'Deck2' is inserted, then it should be added to form
{
id: "a",
deck_list: [{
name: 'Deck1',
job: 'mage',
cards: []
},
{
name: 'Deck2',
job: 'mage',
cards: []
}],
match: []
}
But when 'Deck1' is added, then old 'Deck1' should be replaced with newer 'Deck1'.
You probably want to make deck_list an object rather than an array, and map from the name of the deck to its job/cards. Then you can use update normally, and it will create the deck if it doesn't exist or update it if it does.
Related
how can I display toasts by traversing an array of objects, each of these objects with a unique id and names. I need to display a toast for each object inside this array, with a text and the value {item.name}.
Example:
https://codesandbox.io/s/exciting-cloud-9oqhke?file=/src/App.js:0-583
In this example I used the React-toastify, and added the array of objects as an example, in that example there is a button that launches one toast with ALL names on it, but I need to press that button and it displays a toast for each object inside the array.
So you can call toast.error function for each array object like this
const testData = [
{ id: 1, name: "John Doe" },
{ id: 2, name: "Victor Wayne" },
{ id: 3, name: "Jane Doe" }
];
testData.map((user) => (
toast.error(`${user.name} ${someText}`)
));
Sup,
So I have this object:
data: {
OtherFields: {},
Skills: [
{
id: Math.random(),
name: 'Default Category',
skills: [],
},
],
{
So the Skills Array is very dynamic, I need to add categories, and each categories have their own array named skills, that will be filled with other objects, and the default category is there.
While the skills inside will have:
{
id: Math.random(),
skillName: 'Default Category',
}
What I want to do is add the skill to the specific category in a dynamic way with the id category as we don't know how much the user will add.
Here what I did until now:
const handleAdd = (id, content) => {
// id is the cateogry of that specific cateogry that im receiving from input
// content is the value of the input
// this is the object i need to push into the category
const newItem = {
id: Math.random(),
skillName: content,
};
// and then update it,
const newData = data.Skills.find((i) => i.id === id);
console.log(newData)
newData.skills.push(newItem);
setData({ ...data, Skills: [...data.Skills, newData] });
//this it works but adds another cateogry and doesnt not replace the current one with the new value that is added
};
This appends newData to the array:
Skills: [...data.Skills, newData]
But it doesn't filter that same record from the array when appending it. It basically means "the whole array as-is, plus this new element". Even if that element is conceptually a duplicate, the code doesn't know that. (Heck, even if it's by reference a duplicate, there's still nothing stopping an array from containing two references to the same object.)
It sounds like you want to filter that whole array to remove that element before re-appending it. For example:
Skills: [...data.Skills.filter(s => s.id !== newData.id), newData]
Since you're modifying the original object this should work, rename your variables to make it easier to read.
Also consider not changing the original object.
setData({ ...data, Skills: [...data.Skills] });
Is it possible to have more than one localStorage.getItem in state?
Right now I have this:
const [list, useList] = useState(
JSON.parse(localStorage.getItem("dictionary")) || [] //tasks in my to-do
);
and I should also keep in this state my subtasks, contained in a task, with this structure:
- task {
- id
- body
- subtasks
[{
- id
- body
}]
}
Can I save also the subtasks in local storage and access them with getItem?
These are what I want to use to get my subtasks:
JSON.parse(localStorage.getItem("domain")) || []
JSON.parse(localStorage.getItem("range")) || []
Yes, you can have more than one array of values in local storage. You need to set the item before you can access it though, you should also serialize the object or array to a string when saving it.
localStorage.setItem("dictionary", JSON.stringify([]));
localStorage.setItem("domain", JSON.stringify([]));
localStorage.setItem("range", JSON.stringify([]));
alert(JSON.parse(localStorage.getItem("dictionary")));
alert(JSON.parse(localStorage.getItem("domain")));
alert(JSON.parse(localStorage.getItem("range")));
Lucky me, I saw your other question which contains a running code snippet, you should add it here too!
From what I saw you're trying to create a tree of tasks, dictionary is a task and it can have subtasks such as domain and range, right? Then you should have a data structure like this:
singleTask = {
id: 0,
body: "task",
domain: [
{
id: 00,
body: "subtask domain 1"
},
{
id: 01,
body: "subtask domain 2"
}
],
range: [
{
id: 10,
body: "subtask range 1"
},
{
id: 11,
body: "subtask range 2"
}
]
}
When you're rendering a task as TaskListItem, you render the task.body. Then pass task.domain to a SubtaskDomain component, task.range to a SubtaskRange component.
When you submit a subtask, update the main list in App, after you do that, update local storage, you already do that, but you actually only need one set item, and it's
localStorage.setItem("dictionary", JSON.stringify(listState));
because you have everything in it!
I have a pre-rendered array of agenda items to which a user can add items and also type in what position in the agenda the item should have.
The array in the constructor:
this.agendaItems = [{
id: 1,
subject: 'Opening of the meeting'
}, {
id: 2,
subject: 'Election of chairman'
}, {
id: 3,
subject: 'Approval of the agenda'
}, {
id: 4,
subject: 'Presentation of the annual report and audit report'
}, {
id: 5,
subject: 'Adjurnement of the meeting'
},
];
And the method for pushing the agendaItem to the array:
saveAgendaItem(num: number, subj: string) {
var item = {id: num, subject : subj}
this.agendaItems.push(item);
}
This works but here is my problem: Lets say the user want to add a new item to position 4 (id). I need to:
Sort and the display the items in order by id.
Push the previous item no 4 to position 5 and also
Re-write the id's for all the items that comes after the new item.
I'm not sure how to achieve this in typescript.
Any ideas?
In principle, changing an 'id' is not a good idea. If ID represents just the position, then maybe you don't need it.
Anyway, regarding the object insertion, you may need to use splice (See How to insert an item into an array at a specific index?)
It would be something like: this.agendaItems.splice(4, 0, item)
Regarding the renumeration, I would suggest to traverse with a for loop all the items from the desired position to the last item, changing the 'id'.
I am new to Angular, so apologies in advance if this seems an obvious question...
I know how to display a simple array of objects using the ng-repeat directive, but I'm not sure how to structure more complex layers of information.
For example: If I wanted to list Premier League football clubs, I could simply create an array of objects, the array listing clubs, with each club being an objects containing key-value pairs on various pieces of information or data relating to that club:
$scope.clubs = [
{
name: "Arsenal",
nickname: "Gunners",
clubBadge: "arsenal.jpg",
founded: "1886"
},
{
name: "Newcastle United",
nickname: "Magpies",
clubBadge: "newcastle.jpg",
founded: "1892"
}
// etc...
]
That's fine. But then what I might want to list the players within each club. For example:
// the following being the team of Newcastle United...
{
GK: "Rob Elliot",
LB: "Paul Dummett",
CB: "Fabricio Coloccini",
CB: "Chancel Mbemba",
RB: "Daryl Janmaat",
LW: "Andros Townsend",
MF: "Georginio Wijnaldum",
MF: "Jack Colback",
RW: "Moussa Sissoko",
ST: "Ayoze Perez",
ST: "Aleksander Mitrovic",
}; // and so on for other clubs...
How would I attach the above object to Newcastle Utd (and likewise for other clubs) in the original array, given that it is only a random index within an unordered array? What would be correct way of structuring this information holistically?
I could take this even further by providing stats on each individual player, such as:
{ // stats for Moussa Sissoko
speed: "86",
ballControl: "71",
strength: "85",
vision: "79"
}
{ // stats for Ayoze Perez
speed: "78",
ballControl: "83",
strength: "69",
vision: "78"
}
Again, I have listed these as individual objects. But I don't know what array to link them to their respective clubs, or how to connect each array (assuming there were three separate arrays: $scope.clubs, $scope.players, $scope.attributes).
If Newcastle Utd is the 10th club in the array, it would be $scope.clubs[9], but I don't want to have to create an entirely new array for the players that has no link to the $scope.clubs[] array. Ideally I want it all to be connected.
Is ng-repeat sufficient to access the model data in these cases or would a more sophisticated directive be required? I'm looking to build the information so it is easy to update and display the data in the view.
Sorry this is a little long-winded - if I knew how to phrase my problem more succinctly, I would!
Any advice here would be massively appreciated. Thanks in advance.
Var clubs = [
{
Name : "clubname",
Players: [
{
Name: "name"
},
{
Name:"othername"
}
];
}
];
enter code here
You can put objects inside objects, with you example will look like this:
$scope.clubs = [
{
name: "Arsenal",
nickname: "Gunners",
clubBadge: "arsenal.jpg",
founded: "1886",
players: [
{
//all the player stuff
},
{
//Other player stuff
}
//Continue with all the players
]
},
{
name: "Newcastle United",
nickname: "Magpies",
clubBadge: "newcastle.jpg",
founded: "1892",
players: [
{
//all the player stuff
},
{
//Other player stuff
}
//Continue with all the players
]
}
// etc...
]
And you can access like this $scope.clubs[0].players, I recommend you to give the clubs an Id, that way is going to be much easier to play with the data. To do this, if you have access to the source you can add it from there, if not, you could use foreach loop on the object and add the Id property