This is a data-structurey kind of question, so I thought this would be a good forum to ask it in. I'm starting to run into the issue below quite a bit. Some service sends me data in the format below. It's an array of people, that tells me what pets they own.
owners = [
{
owner: 'anne',
pets: ['ant', 'bat']
},
{
owner: 'bill',
pets: ['bat', 'cat']
},
{
owner: 'cody',
pets: ['cat', 'ant']
}
];
But what I really want, is an array of pets, and which people have them, like this:
pets = [
{
pet: 'ant',
owners: ['anne', 'cody']
},
{
pet: 'bat',
owners: ['anne', 'bill']
},
{
pet: 'cat',
owners: ['bill', 'cody']
}
];
Is there some tool where I can say, "Transform my input array into an array of unique pet objects, where each output object has a property whose value is an array of owners?"
Or do I need to write this by hand?
You could build a new array with the help of a hash table and iterate all owners and all pets.
var owners = [{ owner: 'anne', pets: ['ant', 'bat'] }, { owner: 'bill', pets: ['bat', 'cat'] }, { owner: 'cody', pets: ['cat', 'ant'] }],
pets = [];
owners.forEach(function (owner) {
owner.pets.forEach(function (pet) {
if (!this[pet]) {
this[pet] = { pet: pet, owners: [] }
pets.push(this[pet]);
}
this[pet].owners.push(owner.owner);
}, this)
}, Object.create(null));
console.log(pets);
.as-console-wrapper { max-height: 100% !important; top: 0; }
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