1

i'm parsing/mapping 2 differents types of data/objects inside i.values:

i can see in console:

(3) [1, 2, 3,__ob__: Observer] 
  0:1
  1:2
  2:3
  length:3
  __ob__: Observer {value: Array(3), dep: Dep, vmCount: 0}
  __proto__:Array

the next type of data/object is:

{__ob__: Observer}
  no: "I'm not"
  not_sure: "I'm not sure"
  yes: "I'm sure"
  __ob__:Observer {value: {…}, dep: Dep, vmCount: 0}

this is my code to parse/map:

this.cstInputs.map(i => {
  i.values = i.values.map((k, v) => {
    return {
      value: v,
      label: k
    }
  });
}

the code are failing in the last object: no: "I'm not"...

Uncaught (in promise) TypeError: i.values.map is not a function...

how can I analyze these different types of data or differentiate them to get a key pair value with other method like map?

thank you

ntj34
  • 65
  • 8

2 Answers2

0

It looks like you will need to determine whether i.values is an array or an object (which does not have a .map() method).

There is a pretty good discussion of that here: In javascript how can we identify whether an object is a Hash or an Array?.

The accepted answer offers this code snippet:

if(i.values.constructor == Array){
}
else if(i.values.constructor == Object){
}
greendemiurge
  • 509
  • 3
  • 11
0

Object doesn't have one method=map(), so it threw up the error Uncaught (in promise) TypeError: i.values.map is not a function.

For your use case, Uses Object.entries should be better.

like below demo:

let cstInputs = [
  {'values': [1, 2, 3]},
  {'values': 
            {
              'no':'I am no', 
              'not_sure': 'I am not sure', 
              'yes': 'I am yes'
            } 
  }
]

let result = cstInputs.map( (i) => {
  return Object.entries(i.values).map( (item) => {
    return {
      value: item[0], 
      label: item[1]
    }
  })
})

console.log(result)
Sphinx
  • 10,519
  • 2
  • 27
  • 45