G
G
GunAlv2021-06-09 16:45:14
JavaScript
GunAlv, 2021-06-09 16:45:14

How to correctly shift the fields of one object to another?

There is a condition object and an error object:

const error = new Error();

const someObject = {
  message: 'Fail',
  count: 3,
};


How to correctly shift fields from someObject to error?

UPD: when copying the type error = { ...error, ...someObject }, the error object ceases to be an error, but becomes a normal object

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
dispache, 2021-06-09
@GunAlv

let error = new Error('hello');

const someObject = {
  message: 'Fail',
  count: 3,
};

console.log(error.message) // hello

error = {...error, ...someObject};

console.log(error.message) // Fail
console.log(error.count) // 3

upd : such an implementation is possible using an additional class that extends the Error class
const someObject = {
  message: 'Fail',
  count: 3,
};

class CustomError extends Error {
    constructor(obj) {
        super();
        for ( let key in obj ) {
            this[key] = obj[key]
        }
    }
}

let error = new CustomError(someObject);

console.log(error) // объект ошибки
console.log(error.message); // Fail
console.log(error.count); // 3

D
Dmitry Markov, 2021-06-09
@En-Tilza

I'm not sure, but maybe so?)
error(...someObject)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question