向对象属性添加新属性

时间:2019-05-29 08:52:49

标签: javascript

我需要为comment属性编写新属性而不删除它。 现在这是我的对象:

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

您需要写的东西:

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

应该如何:

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

我这样做了:

product.comment = author;

但是它删除了text属性。 如何在不删除评论属性的情况下将新属性写入?

4 个答案:

答案 0 :(得分:5)

尝试一下:

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

有关Spread运算符的更多信息,请参见documentation

答案 1 :(得分:1)

您可以使用传播运算符语法,a)保留product.details.comment中已经存在的所有值,b)添加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)

答案 2 :(得分:1)

您可以使用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);

答案 3 :(得分:1)

这是从打字稿编译器获得的简单棘手函数;

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

致电:

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