【问题标题】:Advanced in converting arrays to objects [duplicate]将数组转换为对象的高级[重复]
【发布时间】:2021-12-07 00:25:57
【问题描述】:

我正在努力解决以下 javascript 问题。 有没有这样的方法?

// input, based on this data, I want the output to be like below
const ListValues = ["id", "name", "description"]

// output
const initialValues = {
    id: "",
    name: "",
    description: "",
}; 

非常感谢,祝你有美好的一天

【问题讨论】:

    标签: javascript arrays object converters


    【解决方案1】:

    您可以使用Object.fromEntries()Array.map() 从输入中创建所需的对象。

    const ListValues = ["id", "name", "description"];
    
    const initialValues = Object.fromEntries(ListValues.map(v => [v, '']));
    
    console.log('initialValues:', initialValues)
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    您也可以使用Array.reduce() 来获得相同的结果:

    const ListValues = ["id", "name", "description"];
    
    const initialValues = ListValues.reduce((acc, cur) => { 
        acc[cur] = '';
        return acc;
    }, {})
    
    console.log('initialValues:', initialValues)
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    • 2021-11-04
    • 2019-02-09
    • 2019-07-14
    • 2016-05-22
    • 1970-01-01
    相关资源
    最近更新 更多