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 函数来接收这样的一个数组并构建一个对象,其中 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 }
广告