Let's say I have an array like so:

[ 
  {
    field: "firstname",
    value: "John"
  },
  {
    field: "lastname",
    value: "Doe"
  },
  {
    field: "hobbies",
    value: "singing, basketball"
  },
]

Now I want to convert it into an object like so where in the key is the field and the value is the value from the above array:

 const result = { 
      firstname: "John",
      lastname: "Doe",
      hobbies: "Singing, basketball"
    }

4 Answers

1
Maheer Ali On Best Solutions

map() the array to Object.values and pass it to Object.fromEntries()

const arr = [ { field: "firstname", value: "John" }, { field: "lastname", value: "Doe" }, { field: "hobbies", value: "singing, basketball" }, ]

const res = Object.fromEntries(arr.map(Object.values))
console.log(res)

The another solution could be using reduce()

const arr = [ { field: "firstname", value: "John" }, { field: "lastname", value: "Doe" }, { field: "hobbies", value: "singing, basketball" }, ]

const res = arr.reduce((ac,a) => (ac[a.field] = a.value,ac),{})
console.log(res)

2
Vasil Dininski On

You could use Array.prototype.reduce like so:

const arr = [ 
  {
    field: "firstname",
    value: "John"
  },
  {
    field: "lastname",
    value: "Doe"
  }
];

const obj = arr.reduce((acc, val) => { 
  acc[val.field] = val.value; 
  return acc;
}, {});

This would populate the obj object with the values and fields.

2
Mohammad Usman On

You can use .reduce() method to get the desired output:

const data = [
  {field: "firstname", value: "John"},
  {field: "lastname", value: "Doe"}
];

const result = data.reduce((r, {field: key, value}) => (r[key] = value, r), {});

console.log(result);

1
mukesh kudi On

you can do it with applying simple for loop...

const arr=[ 
        {
         field: "firstname",
         value: "John"
        },
        {
         field: "lastname",
         value: "Doe"
        }
     ];

const obj={} //declare an object

for(let i=0;i<arr.length;i++){
    obj[arr[i].field]=arr[i].value;
  }

alert(obj)  //output : {firstname: "John", lastname: "Doe" }