S
S
Stanislav2016-03-18 20:45:16
Node.js
Stanislav, 2016-03-18 20:45:16

Why is the object overwritten?

Faced a problem and I can not understand why the object is overwritten.
For example, there is a file with a default object
schema.js

schema = {
    "price": {
        "min": 0,
        "max": 99999
    }
};
module.exports = schema;

In the test file, I need to merge two arrays, for this I use npm extend
var extend = require('extend');
var schema = require('./application/config/schema');

var used = {
    "price": {
        "min": 100,
        "max": 2000
    }
};

var clean = extend(true, schema.search, used);

console.log(schema);

In the schema response, I get
price: { min: 100, max: 2000 }
How to prevent changing the contents of the schema?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artem Silantiev, 2016-03-18
@ms-dred

As far as I understand, here it is necessary to create a clone of the object in order not to change the original, apparently something like this:
You can also use Object.assign instead of npm extend:
console.log( Object.assign({}, schema, used) )

K
keslo, 2016-03-18
@keslo

Why do extendyou start using schema.searchand not schema?
It's very good to try this:
What do you need to get as an output?
The official documentation says

Keep in mind that the target object will be modified, and will be returned from extend().
The target object will be changed and will be returned as the result of extend()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question