为对象内的键分配布尔值

时间:2019-04-02 14:05:33

标签: javascript

我试图找到一种方法,以遍历值数组,将每个值另存为键,并为每个键分配一个“ true”布尔值。

目标是创建以下对象:

{
  "arrayValue" : true,
  "anotherArrayValue" : true,
  "arrayValueAsWell" : true
}

我在做:

  var objectToCreate = {};

  let myArray = ["arrayValue", "anotherArrayValue", "arrayValueAsWell"]
  let myArrayConverted = myArray.forEach((prop,index) => objectToCreate[prop] = true)

并获得:

  {
    0 : "arrayValue",
    1 : "anotherArrayValue",
    2 : "arrayValueAsWell"
  }

4 个答案:

答案 0 :(得分:4)

您可以使用Array.prototype.reduce创建具有以下键的对象:

const myObject = ["arrayValue", "anotherArrayValue", "arrayValueAsWell"]
  .reduce((acc, value) => ({ ...acc, [value]: true }), {});

console.log(myObject);

答案 1 :(得分:3)

forEach()的{​​{3}}值为undefined。您还应该使用赋值(=)运算符将值分配给对象键:

var objectToCreate = {};
let myArray = ["arrayValue", "anotherArrayValue", "arrayValueAsWell"];
myArray.forEach(prop => objectToCreate[prop] = true);
console.log(objectToCreate);

答案 2 :(得分:1)

您可以映射对象,并使用Object.assign将它们全部分配给一个对象

var array = ["arrayValue", "anotherArrayValue", "arrayValueAsWell"],
    object = Object.assign(...array.map(k => ({ [k]: true })));

console.log(object);

答案 3 :(得分:0)

您可以迭代数组并分配给objectToCreate,如下所示:

  var objectToCreate = {};
  let myArray = ["arrayValue", "anotherArrayValue", "arrayValueAsWell"];
  myArray.forEach(key => objectToCreate[key] = true)';