【问题标题】:JavaScript React! how to convert array to an array of object in javascript [closed]JavaScript 反应!如何在javascript中将数组转换为对象数组[关闭]
【发布时间】:2018-09-13 14:53:55
【问题描述】:
const myArray =  ['position zero', 'position one', 'position three', 'position four'];

// 我需要把它转换成

const objectArray = [
    {
        position: 'position zero'
    },
    {
        position: 'position one'
    },
    {
        position: 'position three'
    },
    {
        position: 'position four'
    },
];

// 必须与我将引用的所有密钥相同

【问题讨论】:

标签: javascript arrays reactjs


【解决方案1】:

map 覆盖当前数组并从 map 函数返回对象

const myArray =  ['position zero', 'position one', 'position three', 'position four'];

const res = myArray.map(data => {
    return {position: data}
})

console.log(res)

【讨论】:

  • 如果有帮助,请考虑将答案标记为已接受
【解决方案2】:

您可以将array#mapShorthand property names 一起使用。

const myArray =  ['position zero', 'position one', 'position three', 'position four'],
      result = myArray.map(position => ({position}));
console.log(result);
.as-console-wrapper { max-height:100% !important; top:0;}

【讨论】:

    【解决方案3】:

    你可以在这里使用.map()

    const result = myArray.map(s => ({position: s}));
    

    演示:

    const myArray =  ['position zero', 'position one', 'position three', 'position four'];
    
    const result = myArray.map(s => ({position: s}));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    文档:

    【讨论】:

      【解决方案4】:

      用户 array.map 与 ES6 的 shorthand object litteral:

      const myArray =  ['position zero', 'position one', 'position three', 'position four'];
      
      const res = myArray.map(position => ({position}));
      console.log(res);

      【讨论】:

        猜你喜欢
        • 2018-12-21
        • 1970-01-01
        • 2023-01-02
        • 1970-01-01
        • 2019-04-06
        • 2021-12-13
        • 2021-09-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多