0

I had an object with an array of elements:

const item= [{name : a, color : white, status : offline},
            {name : b, color : red, status : offline},
            {name : c, color : yellow, status : online},
            {name : e, color : green, status : online}]

I need to create a new object with only the 'name' properties of the elements who has 'status:online' properties.

Here's my code:

let newItem={};
let objLen=Object.keys(item).length;
for(const i=0;i<=objLen;i++){
 if([item.status][i] === 'online' && [item.status][i] != 'offline'){
  newItem[i]=[item.name][i]
 }
}
console.log(newItem);

The problem is that 'newItem' returns this:

newItem= [{},
         {},
         {name : c},
         {name : e}]

How can I return the object without the empty elements? Like this:

newItem= [{name : c},
         {name : e}]
  • Can you make your code contain a valid array? – epascarello Aug 30 '22 at 16:49
  • filter and map or reduce with push – epascarello Aug 30 '22 at 16:50
  • valid array ready – Omar Anaya Aug 30 '22 at 17:03
  • use `lodash` or alike libraries for this type of methods. `const grouped = groupBy(item, i => i.status); // { online: [], offline: [] }` then just map your value `const namesArray = map(grouped.offline, ({ name }) => name` or `({ name }));` P.S: you can do this with array reduce or just using for loop, but my personal preference is to use library or util function – Aykhan Huseyn Aug 30 '22 at 17:21

0 Answers0