Comfort Eagle
Comfort Eagle

Reputation: 2472

Vue/Vuex: Distinguish arrays from objects in Proxy objects

As stated here, reactive Vuex objects are returned as Proxy objects. This may not be a problem in most cases, but how do I determine if the Proxy originated from an array or object?

Upvotes: 1

Views: 477

Answers (1)

tony19
tony19

Reputation: 138556

The Proxy is a transparent layer on top of the array/object, so you would not need to determine the Proxy's original source.

The variable itself should be treated as if the Proxy layer were not there. If it's a Proxy of an Array, treat the variable as an Array, and the same for Object. Run the following code snippet for examples.

const arr = [1,2,3]
const arrProxy = new Proxy(arr, {})             // value is identical to `arr`
console.log(arrProxy.map(x => x * 10))          // => [ 10, 20, 30 ]
console.log('isArray', Array.isArray(arrProxy)) // => true

const obj = { foo: true, bar: false }
const objProxy = new Proxy(obj, {})            // value is identical to `obj`
console.log(Object.keys(objProxy))             // => [ 'foo', 'bar' ]
console.log('objArray type:', typeof objProxy) // => object

Upvotes: 2

Related Questions