Q: How to convert array to object using loop (forEach, map, etc..) in Javascript From
[
  {
    "id": "0001",
    "name": "Jack",
    "completeName": "Jack Smith"
  },
  {
    "id": "0002",
    "name": "Mary",
    "completeName": "Mary Jackson"
  },
  {
    "id": "0003",
    "name": "John",
    "completeName": "John Doe"
  }
]

to this:
{
  "Jack" :{
    "id": "0001",
    "name": "Jack",
    "completeName": "Jack Smith"
  },
  "Mary" : {
    "id": "0002",
    "name": "Mary",
    "completeName": "Mary Jackson"
  },
  "John": {
    "id": "0003",
    "name": "John",
    "completeName": "John Doe"
  }
}


A: 1. using forEach :


var data = [{
    "id": "0001",
    "name": "Jack",
    "completeName": "Jack Smith"
  },
  {
    "id": "0002",
    "name": "Mary",
    "completeName": "Mary Jackson"
  },
  {
    "id": "0003",
    "name": "John",
    "completeName": "John Doe"
  }
];

var result = {};
data.forEach(function(val) {

  result[val["name"]] = val;

});

console.log(result);


2. Using object.assign and map:


var data = [{
    "id": "0001",
    "name": "Jack",
    "completeName": "Jack Smith"
  },
  {
    "id": "0002",
    "name": "Mary",
    "completeName": "Mary Jackson"
  },
  {
    "id": "0003",
    "name": "John",
    "completeName": "John Doe"
  }
];
let dictionary = Object.assign({}, ...data.map((x) => ({
  [x.name]: x
})));
console.log(dictionary);



A: You can use .map() and Object.fromEntries().


var data = [{
    "id": "0001",
    "name": "Jack",
    "completeName": "Jack Smith"
  },
  {
    "id": "0002",
    "name": "Mary",
    "completeName": "Mary Jackson"
  },
  {
    "id": "0003",
    "name": "John",
    "completeName": "John Doe"
  }
];

var result = Object.fromEntries(data.map(el => [el.name, el]));

console.log(result);



A: You can use an array reduce method.
Array.prototype.reduce()


const test = [
  {
    "id": "0001",
    "name": "Jack",
    "completeName": "Jack Smith"
  },
  {
    "id": "0002",
    "name": "Mary",
    "completeName": "Mary Jackson"
  },
  {
    "id": "0003",
    "name": "John",
    "completeName": "John Doe"
  }
];

const results = test.reduce((obj, props) => {
  obj[props.name] = props;
  return obj;
} , {});

console.log(results);



A: You need to take your data, let's say it's stored in the data variable, and reduce() it with this one-liner:
const output = data.reduce((acc, row) => ({ ...acc, [row.name]: row }), {} );



const data = [
  {
    id: '0001',
    name: 'Jack',
    completeName: 'Jack Smith',
  },
  {
    id: '0002',
    name: 'Mary',
    completeName: 'Mary Jackson',
  },
  {
    id: '0003',
    name: 'John',
    completeName: 'John Doe',
  },
];

const output = data.reduce((acc, row) => ({ ...acc, [row.name]: row }), {});

console.log(output);


