【问题标题】:Convert Dict to Array [closed]将字典转换为数组 [关闭]
【发布时间】:2021-08-07 09:01:15
【问题描述】:

当我想将数组转换为 dict 时,它会将 const 的名称放入其中。

想要转换这个:

const hallo = {'name': 'Peter', 'lastname': 'Richard'}

收件人:

const arrayhallo = [{'name': 'Peter', 'lastname': 'Richard'}]

我试着做这样的事情:

const arrayhallo = [{hallo}]

但它会返回:

[hallo: {'name': 'Peter', 'lastname': 'Richard'}]

我只希望将字典放入数组中,但使用 .push 或这种方式我会不断获取字典的第一个名称作为索引。

【问题讨论】:

  • [{ ...hallo }][ hallo ]

标签: javascript arrays reactjs dictionary


【解决方案1】:

试试这个。

let array1 = []
const hello = {'name': 'Peter', 'lastname': 'Richard'}
array1.push(hello)
console.log(array1)

【讨论】:

    【解决方案2】:

    答案很简单:

    分配一个数组,其中唯一的项目是对象的变量应该可以完成这项工作

    const hallo = {'name': 'Peter', 'lastname': 'Richard'};
    const arrayhallo = [hallo];
    console.log(arrayhallo); // will return [{'name': 'Peter', 'lastname': 'Richard'}]
    

    然后您可以使用 arrayhallo.push(object) 将其他对象添加到数组中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-24
      • 2016-09-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-21
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多