admin管理员组文章数量:1323512
An object is like:
const obj = [{name: 'Alex', age: 20}, {name: 'James', age: 22}];
This obect is immutable from Immutable.js.
Is it possible to add a new key for each object? example:
const obj = [{name: 'Alex', age: 20, city: 'New York'}, {name: 'James', age: 20, city: 'Rome'}];
An object is like:
const obj = [{name: 'Alex', age: 20}, {name: 'James', age: 22}];
This obect is immutable from Immutable.js.
Is it possible to add a new key for each object? example:
const obj = [{name: 'Alex', age: 20, city: 'New York'}, {name: 'James', age: 20, city: 'Rome'}];
Share
Improve this question
edited Sep 16, 2018 at 7:36
NAVIN
3,3174 gold badges20 silver badges32 bronze badges
asked Sep 15, 2018 at 13:12
Eugenio SegalaEugenio Segala
891 silver badge6 bronze badges
3
- What happens if you simply try adding properties to each object? – Pointy Commented Sep 15, 2018 at 13:15
- 3 "This obect is immutable from Immutable.js" - the snippet you posted does not use immutable.js, it just creates normal array and object literals. Can you post some code that creates a real Immutable object? – Bergi Commented Sep 16, 2018 at 8:17
- Is your question answered? If so, mark the correct answer. If not, ment on the answers given and specify why those don't answer your question. – connexo Commented Sep 17, 2018 at 8:04
2 Answers
Reset to default 7Not if it’s immutable. But that is ok, you can copy all the properties over to a new structure and add whatever you need to that way:
const newData = obj.map(person => ({
...person,
city: someLogicToDetermineCity(person)
}))
function someLogicToDetermineCity(person) {
// logic based on person
return city
}
const
doesn't create immutability - it just means that the reference assigned to it on creation cannot be changed later (which simply means that you cannot assign a new value to it).
See these examples:
const a = {}
a = { name: "peter" } // => TypeError: invalid assignment to const `a'
However it's no problem to assign a property on a
:
const a = {}
a.name = "peter"
console.log(a); // => { "name": "peter" }
The same applies for Array
objects:
const arr = [{}]
arr.push(1);
arr[0].name="peter"
console.log(arr);
// [
// {
// "name": "peter"
// },
// 1
// ]
本文标签: reactjsCan we add properties to immutable object in JavaScriptStack Overflow
版权声明:本文标题:reactjs - Can we add properties to immutable object in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742135695a2422357.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论