Iterate through object properties with Symbol keys
Asked Answered
P

3

30

I need to iterate through an object that has Symbols for keys. The following code returns an empty array.

const FOO = Symbol('foo');
const BAR = Symbol('bar');

const obj = {
  [FOO]: 'foo',
  [BAR]: 'bar',
}

Object.values(obj)

How can I iterate the values in obj so that I get ['foo', 'bar']?

Putout answered 18/11, 2017 at 23:45 Comment(2)
check Object.getOwnPropertySymbols(obj)Shahaptian
developer.mozilla.org/de/docs/Web/JavaScript/Reference/…Nye
P
33

You can iterate over all the keys of Object (String and Symbol keys) with

Reflect.ownKeys()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/ownKeys

Pastoralize answered 7/12, 2019 at 11:59 Comment(0)
R
28

Object.values only gets the values of all enumerable named (string-keys) properties.

You need to use Object.getOwnPropertySymbols:

console.log(Object.getOwnPropertySymbols(obj).map(s => obj[s]))
Rosinski answered 19/11, 2017 at 13:27 Comment(0)
R
0
const FOO = Symbol('foo');
const BAR = Symbol('bar');

const temp3 = [
{
  id: 123,
  name: "John",
  [FOO]: 'foo',
  [BAR]: 'bar',
},
{
  id: 456,
  name: "Peter",
  [FOO]: 'foo',
  [BAR]: 'bar',
}
]
const horror = temp3.map((item) => {
    return {
        ...item,
        ...Object.getOwnPropertySymbols(item).reduce((acc, i) => ({ ...acc, [i.toString()]: item[i] }), {})
    }
})

console.log(JSON.stringify(horror, null, 2))

returns:

[
  {
    "id": 123,
    "name": "John",
    "Symbol(foo)": "foo",
    "Symbol(bar)": "bar"
  },
  {
    "id": 456,
    "name": "Peter",
    "Symbol(foo)": "foo",
    "Symbol(bar)": "bar"
  }
]
Roxanaroxane answered 20/2, 2024 at 15:8 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.