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.

5 Answers 5

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);

Sign up to request clarification or add additional context in comments.

1 Comment

i'll test now but since you took out the time i'll upvote anyways thanks.:)
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)

1 Comment

i'll test now but since you took out the time i'll upvote anyways thanks.:)
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)

Comments

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)

2 Comments

i'll test now but since you took out the time i'll upvote anyways thanks.:)
You must not use a big "L"
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.