简体   繁体   中英

Get all truthy values from an array of objects

I want to get all truthy values from an array of objects:

 const users = [{ name: 'string', val: false, }, { name: true, val: [], } ] const identifiers = users.map(i => Object.entries(i)) const active = identifiers.filter(function(id) { const t = id.map((i, k) => id[k][1]) return t }) console.log(active)

The idea of the code above at the end to use Object.fromEntries() and to get something like this:

 const users = [{ name: 'string, }, { name: true, } ]

At the moment i am blocked and i can't get the expected values. Who can help to get the expected result?

You can use Object.fromEntries to create an object using just the properties that are truthy :

 const users = [{ name: true, val: false, }, { name: true, val: true, } ] const identifiers = users.map(e => { // Map User array return Object.fromEntries( // return new object for every element Object.entries(e).filter((o) => o[1] === true) // object constructed using just truthy values by filtering object o[1] -> value ) }); console.log(identifiers)

Or a beautiful one liner:

const identifiers = users.map(e => Object.fromEntries(Object.entries(e).filter(([_,o]) => o)));

You can use reduce method with Object.entries and Object.fromEntries

let result = users.reduce((acc,i) => { 
                 let obj = Object.entries(i).filter(([k,v]) => v); 
                 acc.push(Object.fromEntries(obj)); 
                 return acc;  
               }, [])

console.log(result);

You can decompose, filter and reconstruct the objects like this:

 const users = [{name:true,val:false,},{name:true,val:[],dd:0,ee:1,ff:[0,1]}], res = users.map(i => Object.fromEntries(Object.entries(i).filter(([_,v])=>.Array.isArray(v)&&v || v.length)) ) console.log(res)

This should do the trick:

const newData = users.map(user => {
  return Object.keys(user).reduce((obj, key) => {
    if (user[key]) { //for strict truthy, make user[key] === true
      obj[key] = user[key];
    }
    return obj;
  } ,{});
});

That will:

  1. Perform the object filter operation on each element of the array (map).
  2. Iterate over each key of the object (Object.keys(user).reduce)
  3. Only add a key value pair if the value is truthy.

Note that this will return a new structure, not modify the existing one. I saw the update to the question and put a comment in the code accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM