Reputation: 5220
I have multidimensional array that I would like to have immutable. However I am still not quite sure how am I supposed to work with multidimensional immutable objects.
Lets say that I have structure similar to this one:
// data
{
// item
{
name: someName,
todos: [
{ id: 1, name: todoName },
{ id: 2, name: todoName2 }
]
}
}
How can I extract unique list of todos?
// Saving todos
let uniqueTodos = []
// Saving ids of todos
let saved = []
// I want to make data immutable list
data.forEach(item => {
item.todos.forEach(todo => {
if (saved.indexOf(todo.id) === -1) {
saved.push(todo.id)
todos.push(todo)
}
})
})
return todos
Upvotes: 0
Views: 98
Reputation: 2109
I believe you are confusing two related concepts: immutability - a technique which can be used in JS vs Immutable.js - a library to make the former easy.
Here's an example of both (dataset is corrected a bit to valid JS and to include a duplicate todo):
const data = {
item: {
name: 'someName',
todos: [
{ id: 1, name: 'todoName' },
{ id: 2, name: 'todoName2' },
{ id: 2, name: 'todoName2' },
],
},
}
console.info(
'immutable unique todos:',
data.item.todos.map((todo) => ({ ...todo, }))
)
console.info(
'Immutable.js unique todos:',
Immutable.fromJS(data).getIn(['item', 'todos']).toSet().toJS()
)
<script src="https://cdn.jsdelivr.net/immutable.js/3.8.1/immutable.min.js"></script>
Immutable.js docs.
Upvotes: 4