Search code examples
javascriptarraysobject

JavaScript -- how to iterate through an array of objects to create a new object whose key is the value of the original object's initial key/value pair


Here is my situation:

I have to implement a function "mapById", which, when given an array of objects, returns an object, where the keys are the ids of the input objects and the values are the corresponding input objects.

var input = [{id: 102, name: "Alice"},
             {id: 205, name: "Bob", title: "Dr."},
             {id: 592, name: "Claire", age: 32}];

console.log(mapById(input));

should give the result below:

102: {id: 102, name: "Alice"},
205: {id: 205, name: "Bob", title: "Dr."},
592: {id: 592, name: "Claire", age: 32}

Here is my function thus far:

function mapById(list) {
    var obj = {};
    var objectKey = '';
    list.forEach(function(item) {
        objectKey = (Object.values(item)[0]);
        var obj = {[objectKey]: item};
    });
    return obj;
}

I can get a new key/value pair for each object in the original array but I can't figure out how to add each new key/value pair to the new object.

ObjectKey: 102
item: { id: 102, name: 'Alice' }
obj: { '102': { id: 102, name: 'Alice' } }
ObjectKey: 205
item: { id: 205, name: 'Bob', title: 'Dr.' }
obj: { '205': { id: 205, name: 'Bob', title: 'Dr.' } }
ObjectKey: 592
item: { id: 592, name: 'Claire', age: 32 }
obj: { '592': { id: 592, name: 'Claire', age: 32 } }

How can i fix this? If this was an array I could use the 'push' method. Is there a similar method for objects? Do I need a closure? I know this is basic stuff but I'm quite new to javascript.

Thanks.


Solution

  • You are actually quite close:

    function mapById(list) {
        var obj = {};
        list.forEach(function(item) {
            obj[item.id] = item;
        });
        return obj;
    }
    

    How i would do that:

     const result = Object.fromEntries(input.map(el => ([el.id, el])));