如何使用映射的键值对将数组转换为JavaScript中的对象?

时间:2019-04-29 11:22:36

标签: javascript arrays

假设我有一个像这样的数组:

[ 
  {
    field: "firstname",
    value: "John"
  },
  {
    field: "lastname",
    value: "Doe"
  },
  {
    field: "hobbies",
    value: "singing, basketball"
  },
]

现在我想将其转换为这样的对象,其中上述数组中的键是field,值是value

 const result = { 
      firstname: "John",
      lastname: "Doe",
      hobbies: "Singing, basketball"
    }

4 个答案:

答案 0 :(得分:2)

您可以像这样使用Array.prototype.reduce:

const arr = [ 
  {
    field: "firstname",
    value: "John"
  },
  {
    field: "lastname",
    value: "Doe"
  }
];

const obj = arr.reduce((acc, val) => { 
  acc[val.field] = val.value; 
  return acc;
}, {});

这将使用值和字段填充obj对象。

答案 1 :(得分:2)

您可以使用.reduce()方法来获得所需的输出:

const data = [
  {field: "firstname", value: "John"},
  {field: "lastname", value: "Doe"}
];

const result = data.reduce((r, {field: key, value}) => (r[key] = value, r), {});

console.log(result);

答案 2 :(得分:1)

您可以通过应用简单的for循环来实现...

const arr=[ 
        {
         field: "firstname",
         value: "John"
        },
        {
         field: "lastname",
         value: "Doe"
        }
     ];

const obj={} //declare an object

for(let i=0;i<arr.length;i++){
    obj[arr[i].field]=arr[i].value;
  }

alert(obj)  //output : {firstname: "John", lastname: "Doe" }

答案 3 :(得分:1)

map()Object.values的数组并将其传递到Object.fromEntries()

const arr = [ { field: "firstname", value: "John" }, { field: "lastname", value: "Doe" }, { field: "hobbies", value: "singing, basketball" }, ]

const res = Object.fromEntries(arr.map(Object.values))
console.log(res)

另一个解决方案可能是使用reduce()

const arr = [ { field: "firstname", value: "John" }, { field: "lastname", value: "Doe" }, { field: "hobbies", value: "singing, basketball" }, ]

const res = arr.reduce((ac,a) => (ac[a.field] = a.value,ac),{})
console.log(res)