0

hi so i followed this question : Convert Array to Object: but apparently there are great answers but not what i require. I have an array like this : ["123","jhon","doe","hawaii"] What i want to be able to do is make an object that looks like this : {id:"123",fname:"jhon",lname:"doe",location:"hawaii"}

Basically i want to assign the values of the array to fix keys for each value. I tried looping over them but that would replace the current object key if i do something like.

let obj = {}
arr.map(val=>{
 obj.id = val
})

This will obviously not work. Any ideas or can you point me in the right direction would also help thank you.

Hadi Pawar
  • 1,090
  • 1
  • 11
  • 23

5 Answers5

1

Using the for-loop over the array to add to a new object the properties. The name of the properties are stored in a const-array, so you can add more later if necessary. The number of elments had to be same in both arrays.

let arr = ["123","jhon","doe","hawaii"];
const KEYS = ['id', 'fname', 'lname', 'location']; 
let obj = {};

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

console.log(obj);
Sascha
  • 4,576
  • 3
  • 13
  • 34
1

You'll need a second array of keys (in your example you're trying to define every value to the key id) which is the same size as the data-array, and then between the two of them you can generate an object:

var values = ['123', 'jhon', 'doe', 'hawaii'];
var keys = ['id', 'fname', 'lname', 'location'];
var obj = {};
for (var i = 0; i < values.length; i++) {
   obj[keys[i]] = values[i];
}
console.log(obj)
Rudu
  • 15,682
  • 4
  • 47
  • 63
1

Using Array#reduce() and computed properties

const values = ["123", "jhon", "doe", "hawaii"],
      keys = ["id", "fname", "lname", "location"];

const res = keys.reduce((a, c, i) => ({...a, [c] : values[i]}), {})

console.log(res)
charlietfl
  • 170,828
  • 13
  • 121
  • 150
1

Here's an interesting way to solve it.

keys = ["id","fname","lname","location"];
values = ["123","jhon","doe","hawaii"];
obj = {};
keys.forEach((key, i) => (obj = {...obj, [key]: values[i]}));

console.log(obj)
Ajeet Eppakayala
  • 1,186
  • 1
  • 10
  • 17
0

Here is the solution for your yehr

keys = ["id","fname","lname","location"];
values = ["123","jhon","doe","hawaii"];
var result = {};
keys.forEach((key, i) => result[key] = values[i]);
console.log(result)
Azaz Khan
  • 637
  • 1
  • 8
  • 20