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?

Shira
  • 394
  • 1
  • 6
  • 21
  • 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. – evolutionxbox Sep 08 '20 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 – Andreas Sep 08 '20 at 11:26
  • Does this answer your question? [Is there an \_\_repr\_\_ equivalent for javascript?](https://stackoverflow.com/questions/24902061/is-there-an-repr-equivalent-for-javascript) – hl037_ Sep 08 '20 at 11:27
  • use `JSON.stringify` – Devsi Odedra Sep 08 '20 at 11:27
  • You can map the values to strings, `Object.values(obj).map(String)` if you want an array of strings...? – Nick Parsons Sep 08 '20 at 11:30

1 Answers1

1

You may try out template strings:

const result = Object
                .values({
                   key1: false,
                   key2: "",
                   key3: undefined,
                   key4: null
                })
                .map(v => `${v}`)

console.log(result)
Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
  • I was thinking `Object.values(obj).map(el => el?el:`${el}`)` – Alan Omar Sep 08 '20 at 11:33
  • true that is right. – Alan Omar Sep 08 '20 at 11:35
  • @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 – Shira Sep 08 '20 at 14:55
  • @Yevgen Gorbunkov Solved it with this one: Object.values(item).map(v => !v ? `${v}`: v===true ? `${v}`: v); – Shira Sep 08 '20 at 14:58