Javacsript React!如何在javascript中将数组转换为对象数组

时间:2018-04-04 06:36:32

标签: javascript arrays reactjs

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

//我需要将其转换为

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

//必须是我将引用所有

的相同密钥

4 个答案:

答案 0 :(得分:3)

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



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

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

console.log(res)




答案 1 :(得分:0)

您可以将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;}




答案 2 :(得分:0)

您可以在此处使用.map()

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

<强>演示:

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

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

console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

<强>文档:

答案 3 :(得分:0)

用户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);