Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we add properties to immutable object in JavaScript?

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'}];
like image 566
Eugenio Segala Avatar asked Feb 12 '26 10:02

Eugenio Segala


2 Answers

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
}
like image 68
Ben Steward Avatar answered Feb 14 '26 23:02

Ben Steward


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
// ]
like image 37
connexo Avatar answered Feb 14 '26 22:02

connexo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!