I have an object
const object = {
name:'XYZ',
Others: 'XYZ',
numbers:[2,3,4,5,6,5]
}
I want to filter numbers array which is inside the object and return the object with filtered array like this in which array has numbers 5 only.
{
name:'XYZ',
Others: 'XYZ',
numbers:[5,5]
}
If I use filter in JavaScript like this
object.numbers.filter()
It returns only numbers array not complete object with other details like name. What is the best way to implement it?
CodePudding user response:
Just assign object.numbers
with filter
return like:
const object = {
name:'XYZ',
Others: 'XYZ',
numbers:[2,3,4,5,6,5]
};
object.numbers = object.numbers.filter(el => el === 5);
console.log(object);
CodePudding user response:
to make it work with this.setState
you have to create a new Object:
let object = {
name:'XYZ',
Others: 'XYZ',
numbers:[2,3,4,5,6,5]
}
let updatedObject = {...object,numbers:object.numbers.filter(e => e === 5)}
console.log(updatedObject)
// this.setState(updateObject)