skip to Main Content

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


  1. The map always returns new array of the same length. you can either get your result with the filter or reduce.

    const newData = data && data.filter(item => item.label !== 'c');
    

    OR

        const newData = data && data.reduce((acc, item) => {
         if (item.label !== 'c') {
          acc[item.label] = item;
         }
         return ACC;
        }, {});
    
    Login or Signup to reply.
  2. You are also used this method:

    const data = {
      first: { label: "a", status: true, text: "dummy" },
      second: { label: "b", status: true, text: "dummy" },
      third: { label: "c", status: false, text: "dummy" }
    };
    
    const filteredData = Object.fromEntries(
      Object.entries(data).filter(([key, value]) => value.label !== 'c')
    );
    
    Login or Signup to reply.
  3. 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:

    const data = { 
     first : { label :"a" , status : true , text: "dummy" },
     second : { label :"b" , status : true , text: "dummy" },
     third : { label :"c" , status : false , text: "dummy" }
    }
    
    const newData = Object.entries(data).reduce((accumulator, [key, value]) => {
      if (value.label !== 'c') {
        accumulator[key] = value;
      }
      return accumulator;
    }, {});
    
    console.log(newData);

    in this code Object.entries(data) transforms your object into an array of key-value pairs. The reduce function then goes through these pairs one by one. If it finds a label 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 to newData.

    So, your newData object will look like this:

    { 
     first : { label :"a" , status : true , text: "dummy" },
     second : { label :"b" , status : true , text: "dummy" } 
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search