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.
keys() method was introduced in ES6. It takes the object that you want to iterate over as an argument and returns an array containing all properties names (or keys). You can then use any of the array looping methods, such as forEach(), to iterate through the array and retrieve the value of each property.
For getting all of the keys of an Object you can use Object. keys() . Object. keys() takes an object as an argument and returns an array of all the keys.
You have to pass the object you want to iterate, and the JavaScript Object. keys() method will return an array comprising all keys or property names. Then, you can iterate through that array and fetch the value of each property utilizing an array looping method such as the JavaScript forEach() loop.
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.assign(...input.map(el => ({[el.id] : el})));
Use Array.prototype.reduce():
var input = [{id: 102, name: "Alice"},
{id: 205, name: "Bob", title: "Dr."},
{id: 592, name: "Claire", age: 32}]
var output = input.reduce(function(accumulator, item) {
accumulator[item.id] = item
return accumulator
}, {})
console.log(output)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With