简体   繁体   中英

merge objects into one and override the existing object - javascript es6

I have an one object which contains multiple objects like this below:

const productFields = {
    category_id: {
        key: 'category_id',
        label: 'Category',
        uri: '/products/category',
        value: '',
        items: []
    },
    product_name: {
        key: 'product_name',
        label: 'Product Name',
        value: '',
        items: []
    }
};

Now I want to add one more property into product_name object. I am doing the normal way using spread operator.

const newNameFields = { 
    ...productFields.product_name, 
    uri:`/products/${this.$route.params.id}/category/${this.categoryId}`
};

Now, I am creating new object like this:

const newField = Object.assign({}, category_id: productFields.category_id , product_name: newNameFields);

But, is there any good different logic to do that without initialize that many variables and single shot? It is kind of lame logic I am doing.

You can use multiple spreads to add the property uri to product_name :

 const productFields = {"category_id":{"key":"category_id","label":"Category","uri":"/products/category","value":"","items":[]},"product_name":{"key":"product_name","label":"Product Name","value":"","items":[]}}; const paramsId = 'paramsId'; const categoryId = 'categoryId'; const newProductFields = {...productFields, // spread the base object product_name: { // override product_name...productFields.product_name, // add the original product_name uri: `/products/${paramsId}/category/${categoryId}` // add the property } }; console.log(newProductFields);

You can simply set the property if you are ok to mutate the original object.

const productFields = {

    category_id: {
        key: 'category_id',
        label: 'Category',
        uri: '/products/category',
        value: '',
        items: []
    },
    product_name: {
        key: 'product_name',
        label: 'Product Name',
        value: '',
        items: []
    }

};

productFields.product_name.x = 'new value'

If you do not want to mutate the original object you will need to clone the properties and add a new one like you are doing with Spread syntax or Object.assign

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM