exploring the possibilities of pairing various data formats using Javascript and Vue

When parsing and mapping two different types of data or objects within i.values, the console output shows:

(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 or 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}

My code for parsing and mapping looks like this:

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

The issue arises with the last object: no: "I'm not"...

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

Is there a way to analyze these different data types or differentiate them to extract key-value pairs using a method other than map?

Thank you.

Answer №1

When the object does not have the method "map()", it results in the error

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

For your specific scenario, it would be more appropriate to utilize Object.entries.

See the example below:

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)

Answer №2

It appears that the next step would be to determine if i.values is categorized as an array or an object (an entity that lacks a .map() function).

For more information on this topic, there is a thorough discussion available here: Identifying whether an object is a Hash or an Array in JavaScript.

The solution provided suggests using the following code snippet:

if(i.values.constructor == Array){
}
else if(i.values.constructor == Object){
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble looping through Javascript

Hello, I am encountering a problem with some JavaScript code that I am trying to implement. The functions in question are as follows: var changing_thumbs = new Array(); function changeThumb(index, i, thumb_count, path) { if (changing_thumbs[index]) { ...

Using a function as an argument to handle the onClick event

I have a function that generates a React.ReactElement object. I need to provide this function with another function that will be triggered by an onClick event on a button. This is how I call the main function: this._createInjurySection1Drawer([{innerDra ...

What is the method for retrieving a child element using its ID in JavaScript?

Below is the HTML code I am working with: <div id="note"> <textarea id="textid" class="textclass">Text</textarea> </div> I am trying to retrieve the textarea element without using document.getElementById("textid"). This is what I ...

Utilizing Vue3's draggable component to seamlessly incorporate items

My current project involves the use of the vue draggable package, and below you will find the complete component: <template> <div> <button class="btn btn-secondary button" @click="add">Add</button> ...

Maintain user input within the table following a page refresh

I have been working on developing a table that allows users to edit it. I successfully created a script that adds comments to the table, but unfortunately, these comments disappear when the page is refreshed. I understand that I may need some additional to ...

Showcasing pictures with a prominent large image accompanied by two smaller ones on the right side

In my use of Material-ui-next, I am attempting to create images in a specific layout. ------ --------- | | | | 2 | | | | 1 |---| | | | | 3 | ------ --------- I have encountered some unusual issues. 1 - 3 appears below 1 ...

Retrieval is effective in specific situations but ineffective in others

I have encountered an issue with fetching data only when using the async behavior. I am currently in the process of re-building a property booking website that was originally developed using Laravel and a self-built API. The new version is being created wi ...

The concept of AJAX send function and toggling button visibility

I am facing a challenge with a textarea and send button on a panel that is displayed after entering the first character. The visibility of the button is controlled by the isButtonVisible() method. Once clicked, it sends the text from the textarea using the ...

"Modifying the height of an SVG <g> element: A step-by

Is there a way to adjust the height of a g element? Trying to set the height using {params} but it's not responding I made some changes in the comments because the svg is quite large (Scene.js) {/* Transformation */} <g transform="trans ...

Issue with event listener not functioning properly with dynamically created content using AJAX (only using vanilla JavaScript

I used pure javascript AJAX to dynamically load content into the "test" div. However, when I try to click on a child div at index 6, an alert box is not being displayed as expected. How can I fix the issue with the click event not working? The gets functi ...

Updating Rails Partial with JSON Data

Updating a partial by appending fetched Facebook posts using the koala gem requires some code adjustments. Here is an example of how to achieve this: # feed_controller.rb def index end def fb_feed @fb_feed = .. respond_to do |format| format.js { ...

the three.js code runs smoothly on JSfiddle, but it does not seem to be working properly

Check out this basic three.js code snippet for generating custom geometry http://jsfiddle.net/67Lgzjpb/. After attempting to run this code directly in my browser (not via JSFiddle), an error message pops up: TypeError: geom.computeCentroids is not a funct ...

Utilizing AngularJS: Techniques for Binding Data from Dynamic URLs

Just starting out with AngularJS We are using REST APIs to access our data /shop/2/mum This URL returns JSON which can be bound like so: function ec2controller($scope, $http){ $http.get("/shop/2/mum") .success(function(data){ ...

A guide on manually specifying prop types in Vue3 using TypeScript

Is there a way defineComponent({ props: { name: { type: String as PropType<string> } } }) in Vue3 to inform that the props type is { name: string }? What about when multiple components share the same props type? If I define props as: const ...

html form shifting positions based on screen resolution

I have been experimenting with a login screen design for my website recently. I created a form with a fixed position, but as the screen resolution changes, not only does the form's position shift, but also the image moves, causing an unwanted interse ...

Updating a JavaScript global variable within a click event function: A quick guide

I am currently using Javascript and jQuery to retrieve the mouse coordinates of a click event for use in other Javascript functions. The issue I am facing is that global variables set within an event function do not update outside the function, unlike glob ...

Elevate javascript

How can I create a new constructor that will alert the increment value? Any suggestions on how to achieve this? This is the current code snippet: var increment = new Increment(); alert(increment); /* 1 */ alert(increment); /* 2 */ alert(increment + incr ...

Enhance your table with custom styling by incorporating the seanmacisaac table and placing the tbody within a div

I am looking to make adjustments to a Jquery sortable, searchable table created by seanmacisaac. For more information, visit the link: Does anyone know how to set the height of the tbody to a fixed value while allowing vertical scrolling (overflow-y)? & ...

Altering the color of a div based on a specified value condition

I am in need of assistance with a div structure similar to this: <div id="namacoc" tabindex="1" class="filled-text" placeholder="Input your name" contenteditable ></div> <div id="position" tabindex="1" class="filled-text" placeholder="Input ...

Having trouble getting the CSS class to work in MVC4 with jQuery implementation

I recently created a view page where I implemented some jQuery code: <script type="text/javascript"> $(document).ready(function () { var hdrname = $('#headername').text(); alert(hdrname); if (hdrname == "Pending Assignment") { ...