【问题标题】:How to add an element to an existing object如何将元素添加到现有对象
【发布时间】:2019-11-25 21:22:41
【问题描述】:

我有一个对象如下:

{
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'
}

【问题讨论】:

  • 不,这是一个简单的对象,顺便说一下@mplungjan,这不是重复的。
  • 是的,它是这样的打字稿——{ id: 6, url: 'google.com', title: 'abc', actions: 63, status: 'active', method: ' GET', response_type: 'json' }
  • 是的,我很确定

标签: javascript arrays node.js json typescript


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-18
    • 2015-05-02
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多