0

I have this object:

const obj = {
 key1: false,
 key2: "",
 key3: undefined,
 key4: null
}

Now, I want to use Object.values(obj) so I will get an array of values. But false, undefined & null return as an empty string or in the false case it returns 1 or 0.

So I want to convert the object values to strings.

What will be the best way to do so?

5
  • 1
    JSON.stringify(obj) will get you most of the way there, but key3: undefined is being treated as if it had never been defined at all. Commented Sep 8, 2020 at 11:26
  • 3
    "But false, undefined & null return as an empty string or in the false case it returns 1 or 0" - Nope, that's not how Object.values() works Commented Sep 8, 2020 at 11:26
  • Does this answer your question? Is there an __repr__ equivalent for javascript? Commented Sep 8, 2020 at 11:27
  • use JSON.stringify Commented Sep 8, 2020 at 11:27
  • You can map the values to strings, Object.values(obj).map(String) if you want an array of strings...? Commented Sep 8, 2020 at 11:30

1 Answer 1

1

You may try template strings:

const srcObject = {
  key1: false,
  key2: "",
  key3: undefined,
  key4: null
}

const result = Object
  .values(srcObject)
  .map(v => `${v}`)

console.log(result)

Or String()

const srcObject = {
  key1: false,
  key2: "",
  key3: undefined,
  key4: null
}

const result = Object
  .values(srcObject)
  .map(String)

console.log(result)

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

4 Comments

I was thinking Object.values(obj).map(el => el?el:${el})
true that is right.
@Yevgen Gorbunkov It works but some of the object values can be objects or array. So I wrote this: Object.values(obj).map(v => !v ? ${v}: v); But if one of the values will be 'True' it wont go through
@Yevgen Gorbunkov Solved it with this one: Object.values(item).map(v => !v ? ${v}: v===true ? ${v}: v);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.