0

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
  }

2
  • 3
    why 'Bill' instead of 4? Commented Jun 14, 2020 at 18:03
  • @NinaScholz, probably i did not explained correctly, but i want to get if, i key has value to get the value beside the key, but if the key does not have value to get : 0 Commented Jun 14, 2020 at 18:09

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

what means ([k, v]) from map(([k,v])=>[k, v ? v : v.length]?
@AskMen Object.entries() generates key value pair of object, so I have destructured it as [k,v] inside map.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.