0

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"
}
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
catandmouse
  • 11,309
  • 23
  • 92
  • 150

4 Answers4

3

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)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
2

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.

Vasil Dininski
  • 2,368
  • 1
  • 19
  • 31
  • This is will not produce correct result. It will get the last value `Doe`. You should return `acc` using `,`. And also `reduce` doesnot modify original array you should assign it to a variable. – Maheer Ali Apr 29 '19 at 11:36
2

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);
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
1

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" }
mukesh kudi
  • 719
  • 6
  • 20
  • You are declaring implicit globals. You should `let` or `var` before `i` and `const` before `obj` and `arr` – Maheer Ali Apr 29 '19 at 11:37