将自定义属性添加到现有对象

时间:2016-03-18 15:57:11

标签: javascript

我有以下对象,如下所示:

{ dateCreated: Fri Mar 18 2016 16:36:12 GMT+0400 (MUT),
 lastUpdated: Fri Mar 18 2016 16:36:12 GMT+0400 (MUT),
 users: [ '56ebdaad275a88df234a4480' ],
  viewOnlyUsers: [],
 __v: 0,
  owner: '56ebdaad275a88df234a4480',
 editUrl: 'e7f25e3d-be77-4cfa-a928-6af05f06ec44',
 viewUrl: '2669ba21-0e3b-4ac0-a886-74e3fe217af4?view',
 _id: '20c84dde-56b7-43ba-9fd3-510c1d24ba0f' }

如何在Javascript中为此对象添加自定义属性?

我已经尝试了

 workspaces[test] = 'test';

但它不起作用。

1 个答案:

答案 0 :(得分:2)

在属性名称中添加引号:workspaces['test'] = 'test';

然而,这也很好:

var test = 'myProp';
var workspaces = {}; // your object
workspaces[test] = 'test';