【发布时间】: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