JavaScript-将数组转换为键值对
假设我们有一个像这样的数组-
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函数,该函数接受一个这样的数组并构造一个对象,其中名称值是键,而得分值是它们的值。
使用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 }