将字符串数组转换为具有这些字符串作为属性和空值的对象

时间:2021-02-18 16:47:00

标签: javascript arrays object

假设我有这个:

const myArr = ["NAME_A","NAME_B","NAME_C"];

我想将其转换为:

const myObj = {
  NAME_A: null,
  NAME_B: null,
  NAME_C: null,
}

我可以通过初始化一个空对象并通过使用 forEach 或其他东西迭代数组来添加属性来实现,但我相信有一个更有效的解决方案。

2 个答案:

答案 0 :(得分:0)

//I just used the indexes in the array as keys in the object *shrugs*
function arrToObj(arr){ //converting function
  let obj={}
  for(let i=0;i<arr.length;i++){
    obj[arr[i]]=null
  }
  return obj
}

const myArr = ["NAME_A","NAME_B","NAME_C"];
const myObj=arrToObj(myArr)
console.log(myObj)

答案 1 :(得分:0)

您可以使用内联查询条目并从该条目创建对象,例如

Object.fromEntries(["NAME_A","NAME_B","NAME_C"].map((x)=>[x, null]))