0

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.

2 Answers 2

3

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

Yes 2nd approach is preferable. But, i want it in one line approach. Is there any workaround make my logic more user preferable?
what about the first approach?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.