0

I need to write new properties for the comment property without erasing it. This is my object now:

product:
{
  name: 'name',
  briefPDescription: 'text',
  details:
   {
     about: 'text',
     description: 'text',
     comment:
     {
         "text": 'text'
     },
     subDescription: 'text' 
}

What you need to write:

author:
{ 
    name: 'name',
    position: 'text',
    photo: '../avatar.png' 
} 

How should it be:

product: 
{
  name: 'name',
  briefPDescription: 'text',
  details:
  {
     about: 'text',
     description: 'text',
     comment: 
     { 
         text: ''text',
         name: 'name',
         position: 'text',
         photo: '../avatar.png' 
     },
     subDescription: 'text' 
}

I did this:

product.comment = author;

But it deleted the text property. How can I write new properties to the comment property without erasing it?

MegaRoks
  • 898
  • 2
  • 13
  • 30
  • This shuld help....as it's already answered.. https://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically – Vikash Pathak May 29 '19 at 08:58

4 Answers4

5

Try this:

product.details.comment = {...product.details.comment, ...author};

For more info about the Spread operator see the documentation.

ttulka
  • 10,309
  • 7
  • 41
  • 52
1

You can use the spread operator syntax, to a) keep all the value that were already inside product.details.comment, and b) to add the values of author:

var product = {
  name: 'name',
  briefPDescription: 'text',
  details: {
    about: 'text',
    description: 'text',
    comment: {
      "text": 'text'
    },
    subDescription: 'text'
  }
}

var author = {
  name: 'name',
  position: 'text',
  photo: '../avatar.png'
}

product.details.comment = { ...product.details.comment, ...author}

console.log(product)
Kobe
  • 6,226
  • 1
  • 14
  • 35
1

You can use Object.assign

let product={name:'name',briefPDescription:'text',details:{about:'text',description:'text',comment:{"text":'text'},subDescription:'text'}};
let author={name:'name',position:'text',photo:'../avatar.png'};

Object.assign(product.details.comment, author);
console.log(product);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
1

here is a simple tricky function got from typescript compiler;

    var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};

Call:

product = __assign({}, product, { comment: author });