JavaScript - 将数组转换为键值对

javascriptweb developmentfront end technologyobject oriented programming

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

const arr = [
{"name": "Rahul", "score": 89},
   {"name": "Vivek", "score": 88},
   {"name": "Rakesh", "score": 75},
   {"name": "Sourav", "score": 82},
   {"name": "Gautam", "score": 91},
   {"name": "Sunil", "score": 79},
];

我们需要编写一个 JavaScript 函数,该函数接受一个这样的数组并构造一个对象,其中 name 值是键,score 值是其值。

使用 Array.prototype.reduce() 方法从数组构造一个对象。

示例

以下是代码 −

const arr = [
   {"name": "Rahul", "score": 89},
   {"name": "Vivek", "score": 88},
   {"name": "Rakesh", "score": 75},
   {"name": "Sourav", "score": 82},
   {"name": "Gautam", "score": 91},
   {"name": "Sunil", "score": 79},
];
const buildObject = arr => {
   const obj = {};
   for(let i = 0; i < arr.length; i++){
      const { name, score } = arr[i];
      obj[name] = score;
   };
   return obj;
};
console.log(buildObject(arr));

输出

这将在控制台中产生以下输出 −

{ Rahul: 89, Vivek: 88, Rakesh: 75, Sourav: 82, Gautam: 91, Sunil: 79 }

相关文章