Reputation: 11
I have a multidimensional array like this
Owner[0].dog[0].typeOfDog = "shiba inu", Owner[0].dog[1].typeOfDog = "poodle", Owner[0].dog[2].typeOfDog = "samoyan", Owner[1].dog[0].typeOfDog = "poodle", Owner[1].dog[1].typeOfDog = "poodle", Owner[1].dog[2].typeOfDog = "samoyan", Owner[2].dog[0].typeOfDog = "poodle"
I want to create a variable that contains this exact data structure and returns the same list but without any poodles.
For example:
Owner[0].dog[0].typeOfDog = "shiba inu", Owner[0].dog[0].typeOfDog = "samoyan", Owner[1].dog[0].typeOfDog = "samoyan"
I managed to filter it out using Map and Filter but I am unable to keep the same structure. How would I do this?
owners.Map(owner => owner.dogs.filter(dog => dog.typeOfDog !== "poodle"));
This is returning an array of dogs that are not poodles but I would like to get a array of owners each of which have an array of dogs that are not poodles.
Upvotes: 1
Views: 106
Reputation: 22320
you can do that...
const Owner =
[ { dog :
[ { typeOfDog : 'shiba inu' }
, { typeOfDog : 'poodle' }
, { typeOfDog : 'samoyan' }
] }
, { dog :
[ { typeOfDog : 'poodle' }
, { typeOfDog : 'poodle' }
, { typeOfDog : 'samoyan' }
] }
, { dog :
[ { typeOfDog : 'poodle' }
] }
]
, NoPoodles = Owner
.map(({dog})=>({dog: dog.filter(({typeOfDog})=>typeOfDog!=='poodle')}))
.filter(({dog})=>dog.length)
;
console.log( 'result length =', NoPoodles.length )
console.log( NoPoodles )
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}
Upvotes: 0
Reputation: 469
You forgot to return an object instead of an array:
owners.map(owner => (
Object.assign({}, owner, {
dogs: owner.dogs.filter(dog => dog.typeOfDog !== "poodle")
})
));
Upvotes: 0
Reputation: 21638
Use the spread operator to construct a new object and override the dog property.
const OwnersNoPoodles = Owner.map(o => ({...o, dog: o.dog.filter(d => d.typeOfDog !== 'poodle' )}));
Upvotes: 1