【问题标题】:How to set value for all the objects in array for javascript?如何为javascript数组中的所有对象设置值?
【发布时间】:2019-05-29 18:42:14
【问题描述】:

如何为数组中的所有项目设置值?

例如,我有数组:["chin","eng","maths"]

我想设置为{"chin" :true,"eng":true,"maths":true}

小时候推到火力基地。

【问题讨论】:

  • 您的意思是将["chin","eng","maths"] 更改为{"chin" :true,"eng":true,"maths":true} 作为一个结构?还是作为字符串?将[] 更改为{} 的简单事实意味着不同的结构。 ([] = 数组,{} = 对象)

标签: javascript arrays firebase


【解决方案1】:

一种可能的方法是像这样使用Array.reduce()

const input = ["chin", "eng", "maths"];

let obj = input.reduce((acc, item) => (acc[item] = true, acc), {});

console.log(obj);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

或者,您可以使用 spreading,但会在性能上产生一点开销:

let obj = input.reduce((acc, item) => ({...acc, [item]: true}), {});

【讨论】:

  • 每次迭代都会创建一个新对象吗?好像很贵。
  • 可能与不使用 reduce 的情况下做你已经在做的事情一样昂贵
  • “以防万一” - 是的,当解决方案更短、性能更好且可读性相同时,我想这应该是主要答案。
  • @James 是的,你说得对,我已经添加了一个更好的版本,没有传播。
【解决方案2】:

最简单的方法是使用for...of 循环遍历数组并将每个键添加到对象:

const keys = ["chin", "eng", "maths"],
      output = {};

for (const key of keys) {
  output[key] = true;
}

console.log(output)

另一种选择是使用map 创建键值对条目的二维数组。然后使用Object.fromEntries()创建对象

const keys = ["chin","eng","maths"]
const output = Object.fromEntries(keys.map(k => [k, true]))

console.log(output)

【讨论】:

    猜你喜欢
    • 2015-07-17
    • 2021-07-19
    • 2017-07-06
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    相关资源
    最近更新 更多