如何将元素添加到现有对象

时间:2019-07-17 05:38:10

标签: javascript arrays node.js json typescript

我有一个如下的对象:

{
id: 6,
url: 'https://google.com',
title: 'abc',
actions: 63,
status: 'active',
method: 'GET',
response_type: 'json' 
}

现在我想在该对象中再推送一个元素,预期的输出如下:

{
id: 6,
url: 'https://google.com',
title: 'abc',
actions: 63,
status: 'active',
method: 'GET',
response_type: 'json',
new_ele: 'new_data'
}

1 个答案:

答案 0 :(得分:3)

如果您想以最简单的方式做到这一点

var obj = {
id: 6,
url: 'https://google.com',
title: 'abc',
actions: 63,
status: 'active',
method: 'GET',
response_type: 'json' 
}

然后使用obj.new_ele = 'new data',或者如果您的密钥是动态的,则可以使用 obj[new_ele] = 'new data'

否则,如果您的环境支持ES6 /更高版本的ES *语法

使用Object.assign(obj, {new_ele: "new data"});

即使使用传播算子,它也会变成

let newObj = { ...obj, new_ele: 'new data' };
相关问题