object array
{
first : { label :"a" , status : true , text: "dummy" },
second : { label :"b" , status : true , text: "dummy" },
third : { label :"c" , status : false , text: "dummy" }
}
I have the object and map and push inot other object check the object key have label is "c" ,if present then dont push
const newData = data && data.map(item => {
if(item.label !=='c') {
return {
...item,
};
}
});
expected result
{
first : { label :"a" , status : true , text: "dummy" },
second : { label :"b" , status : true , text: "dummy" }
}
3
Answers
The map always returns new array of the same length. you can either get your result with the filter or reduce.
OR
You are also used this method:
We can use
Object.entries
to create an array of the object’s properties, then iterate over this array. Here’s how you can do it using the reduce function, which is pretty neat for this kind of task:in this code
Object.entries(data)
transforms your object into an array of key-value pairs. Thereduce
function then goes through these pairs one by one. If it finds alabel
property that isn’t ‘c’, it adds the key-value pair to the accumulator object. The accumulator object is what we end up with as the result, and we’re assigning it tonewData
.So, your
newData
object will look like this: