将JS数组转换为对象-JavaScript
假设我们有一个像这样的对象数组-
const arr = [ {id: 1, name: "Mohan"}, {id: 2,name: "Sohan"}, {id: 3,name: "Rohan"} ];
我们需要编写一个函数,该函数接受一个这样的数组,并从中构造一个对象,其id属性为键,名称为值
上述数组的输出应为-
const output = {1:{name:"Mohan"},2:{name:"Sohan"},3:{name:"Rohan"}}
示例
以下是代码-
const arr = [ {id: 1, name: "Mohan"}, {id: 2,name: "Sohan"}, {id: 3,name: "Rohan"} ]; const arrayToObject = arr => { const res = {}; for(let ind = 0; ind < arr.length; ind++){ res[ind + 1] = { "name": arr[ind].name }; }; return res; }; console.log(arrayToObject(arr));
输出结果
这将在控制台中产生以下输出-
{ '1': { name: 'Mohan' }, '2': { name: 'Sohan' }, '3': { name: 'Rohan' } }