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
Add a ment  | 

2 Answers 2

Reset to default 7

Not 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