user15022224
user15022224

Reputation:

How can i update some attributes of my object?

I have a object with many attributes but i want to update only three of them so far i am updating like this:

  local.primary = (local.primary).toFixed(3)
  local.second = local.second.toFixed(3)
  local.last =local.last.toFixed(3)

are there any better way?

Upvotes: 0

Views: 39

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370659

If you wanted to be DRY you could use Object.fromEntries and map over an array of the properties to change:

Object.assign(
  local,
  Object.fromEntries(
    ['primary', 'second', 'last'].map(
      prop => [prop, local[prop].toFixed(3)]
    )
  )
);

If you really wanted to spread, I suppose you could do it if reassigning the object or creating a new one is OK:

const newObj = {
  ...local,
  ...Object.fromEntries(
    ['primary', 'second', 'last'].map(
      prop => [prop, local[prop].toFixed(3)]
    )
  )
};

But if there are only 3 properties, I don't think listing them individually is bad at all:

Object.assign(
  local,
  {
    primary: local.primary.toFixed(3),
    second: local.second.toFixed(3),
    last: local.last.toFixed(3),
  }
);

It's not clear what the whole data structure is, but primary, second, and last might be better off as their own standalone property object or array.

Upvotes: 1

Related Questions