Asking
Asking

Reputation: 4192

How to map Array of Objects and return the length of each Object's value?

I want to check the value of every key in each object and write its length.

I tried doing this:

const a = [
  {
    name:"Bill",
    age:'',
    old:''
  }
]
const myF = (arr) => {
  return arr.map((i,k) => {
    console.log(Object.keys(i))
      return{ [Object.keys(i)]: ''}
  })
  
}
console.log(myF(a))

I expect to get:

{
    name:4,
    age:0,
    old:0
  }

Upvotes: 0

Views: 196

Answers (2)

Levi
Levi

Reputation: 859

const a = [
    {
      name:"Bill",
      age:'',
      old:''
    }
  ]
var b = a.map((x) =>{
    if(x.age == '') {
        x.age = 0;
    }
    if(x.old == '') {
        x.old = 0;
    }
    return x;
})
console.log(b)

Upvotes: 0

Rajneesh
Rajneesh

Reputation: 5308

You can map it by taking entries. Let me know if this is what something you need:

var a = [ { name:"Bill", age:'', old:''}];

var result = a.map(obj=>Object.fromEntries(Object.entries(obj).map(([k,v])=>[k, v ? v : v.length])));

var result2 = a.map(obj=>Object.fromEntries(Object.entries(obj).map(([k,v])=>[k, v.length])));

console.log(result);
console.log(result2)

Upvotes: 1

Related Questions