Search This Blog

2024/03/28

Javascript Interview Question:Convert Array (key,value)of Object to Object

Sample Input:
var input = [
{ key: "foo", val: "bar" },
{ key: "hello", val: "world" },
];

Sample Output:
var output = { foo: 'bar', hello: 'world' }

Solution(1st way):
var arr = [
{ key: "foo", val: "bar" },
{ key: "hello", val: "world" },
];

var result = arr.reduce(function (acc, obj) {
acc[obj.key] = obj.val;
return acc;
}, {});
console.log(result)

Output:
{ foo: 'bar', hello: 'world' }

Solution(2nd Way):
var keyValueObjectArray = [
{ key: "foo", val: "bar" },
{ key: "hello", val: "world" },
];

//array
var keyValueArray = keyValueObjectArray.map((elm) => [elm.key, elm.val]);

//array to map
var keyValueMap = new Map(keyValueArray);

//map to object
var result = {}
for (const [key, value] of keyValueMap) {
result[key] = value
}
console.log(result)

Output:
{ foo: 'bar', hello: 'world' }

No comments:

Post a Comment