【问题标题】:Convert array to key value object [closed]将数组转换为键值对象 [关闭]
【发布时间】:2019-05-27 15:37:50
【问题描述】:

我有这种数组

['item one', 'item two', 'item three']

广告想将其转换为这样的对象;

{
"name": 'item one',
"name": 'item two',
"name": 'item three'
}

我尝试循环并创建一个默认键,但我觉得这样做的方式不对

let arr = ['item one', 'item two', 'item three']
let obj = {};
arr.forEach((cv) => { 
  obj["name"] = cv; 
}
console.log(obj)

但这只是返回一个像这样的最后一个值的obj;

{
"name": 'item three'
}

【问题讨论】:

  • 你所问的是不可能的。不能有重复的键。在对象中有重复的键也是没有意义的。
  • 没有这样的对象,键必须是唯一的。将"name" 设置为"item two" 将替换其先前的内容"item one"。换句话说:你的经历是完全正常的。
  • 有什么理由不让"name" 成为一个项目数组吗? IE。 name: [ "item one", "item two", "item three" ]
  • 甚至使用对象数组 [{"name": "items one"}, {"name": "item two"}, ...]
  • 你到底想做什么,你需要这样的结构做什么?正如其他 cmets 已经指出的那样,在 JS 中不能有这样的结构——对象键必须是唯一的。但不清楚的是为什么您需要这个结构开始,最终目标是什么?

标签: javascript arrays object ecmascript-6


【解决方案1】:

为什么是相同的键?对于一个对象,键应该是唯一的。

相反,你可以试试这个,

const arr = ['one', 'two', 'three' ]

let newArr = arr.map(item => {
    return { name: item } })

结果

newArr = [
 { name: 'one' },
 { name: 'two' },
 { name: 'three' },
]

【讨论】:

    猜你喜欢
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 2018-05-10
    相关资源
    最近更新 更多