Creating a JSON object in JavaScript using an array

Can anyone assist me with the following code snippet for formatting the current month?

var monthNames = ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez'];

I have implemented the following logic to achieve the desired month format:

var formatter = new Intl.DateTimeFormat("pt-BR", { month: "short" }),
month1 = formatter.format(new Date()) ; 
var posicao = monthNames.indexOf(month1); 
var mesesSelecionados = monthNames.slice(posicao, 12);  
var mesesSelecionadosJson = {};
var arrayteste=[];
    for ( i =0 ; i< mesesSelecionados.length; i++ ){
        var teste = mesesSelecionados[i].toString();
        mesesSelecionadosJson   =  JSON.stringify({ Mes : mesesSelecionados[i]}, null  );

                arrayteste.push(mesesSelecionadosJson);

                console.log(arrayteste);
                console.log(mesesSelecionadosJson );
                };

I am aiming to obtain this output: [{Mes:"abr"}, {Mes:"mai"}...] (with all values in array)

If you can provide assistance, it would be greatly appreciated. Thank you!

Answer №1

If you want to transform your array into objects, you can use the following method:

var monthNames = ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez'];
var objectArray = monthNames.map(function(month) { return {Month: month}; });
console.log(objectArray);
// Converting to JSON
var jsonOutput = JSON.stringify(objectArray);
console.log(jsonOutput);

// Another way to create the same object structure.
var anotherObjectArray = [{Month:'jan'}, {Month:'fev'}, {Month:'mar'}, {Month:'abr'}, {Month:'mai'}, {Month:'jun'}, {Month:'jul'}, {Month:'ago'}, {Month:'set'}, {Month:'out'}, {Month:'nov'}, {Month:'dez'}];
// You'll notice that this object is identical to the one generated by my solution above.
console.log(anotherObjectArray);

Answer №2

Here is a snippet of my process: and I successfully obtained the desired filter!

var d = new Date();
var ds = d.toLocaleString().substring(6,10);
var formatter = new Intl.DateTimeFormat("pt-BR", { month: "short" }),
        month1 = formatter.format(new Date()) ;
var monthNames = ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez'];
var posicao = monthNames.indexOf(month1);
var selectedMonths = monthNames.slice(posicao, 12);

app1.field('[Year]').selectMatch(ds, true);
app1.field('[Time]').selectMatch("Month", true);
app1.field('[Compare]').selectMatch("Scale", true);
app1.field('[monthstr]').selectValues( selectedMonths, true );

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

"Pair of forms and buttons to enhance user experience with Bootstrap and

Experiencing an issue with my webpage that is built using HTML, Bootstrap, and PHP. The page contains two forms: a contact form and a distribution form within a modal. The problem lies within the distribution form as clicking the button only submits the ...

Schema-based validation by Joi is recommended for this scenario

How can we apply Joi validation to the schema shown below? What is the process for validating nested objects and arrays in this context? const user = { address: { contactName: 'Sunny', detailAddress: { line1: & ...

Storing a reference to children generated by a function within a child prop

I am currently working on a Feed component that accepts a data prop, consisting of an array of items, and a children prop intended for a function that maps the data to a DOM element. My current challenge is implementing the ability to scroll to any elemen ...

Guide to Displaying JSON Objects and Arrays in an Android ListView

I am new to developing Android apps and I'm struggling with how to parse JSON objects and arrays into a ListView in Android. Below is the JSON output: UPDATED WITH CORRECTED JSON {status: "ok", listUsers: [{"id":2,"username":"myusername","name":"myn ...

Aligning a navigation bar with a hamburger menu in the center

I recently implemented a hamburger menu with some cool animations into my site for mobile devices. Now, I am facing the challenge of centering the menu on desktop screens and it's proving to be tricky. The positioning is off, and traditional methods l ...

Async/await is restricted when utilizing serverActions within the Client component in next.js

Attempting to implement an infinite scroll feature in next.js, I am working on invoking my serverAction to load more data by using async/await to handle the API call and retrieve the response. Encountering an issue: "async/await is not yet supported ...

Wrap every character in a span tag within this text

Extracting search strings from an object obj[item].coveredText and replacing each character with a span is what I aim to achieve. Currently, I can only replace the entire search string with a single span element. Any suggestions would be greatly appreciat ...

Repairing the orientation in unique threejs capsule geometric shape

Exploring the realm of custom geometry in three.js, I decided to experiment with modifying Paul Bourke's capsule geometry example. However, as I delve into creating my own custom capsule geometry, I have encountered two main challenges: The orienta ...

What is the best way to dynamically resize a text field based on the length of the typed text

I am looking to dynamically expand the width of an input text field when a user enters text into it. I am not sure how to achieve this functionality. Any guidance or help would be greatly appreciated. Is it possible to do this using Jquery or javascript? ...

Steps for removing a chosen file from several input files by clicking a button

Within my application, there is an input file that displays a list of selected files underneath it. Each of these selected files has a corresponding remove button. While I am able to successfully remove a single file with ease, I struggle when attempting t ...

Guide on how to clear and upload personalized information to Stormpath

After receiving JSON data from my client, I am looking to store it in Stormpath's custom data using node.js with express.js: I have set up a basic post route: app.post('/post', stormpath.loginRequired, function(req, res){ var data = req.b ...

Ensuring Data Completeness: Mandatory Fields based on Boolean Status in JSON Schema Validation

I have searched through numerous resources, but I can't seem to find a solution to my issue. My goal is to validate the specific scenario using a json schema: If 'isRetired' equals false, then additional requirements are retirement age, sa ...

What is the best way to manage classNames dynamically in React with Material-UI?

I am wondering how to dynamically add and remove classes from an img tag. My goal is to change the image automatically every 2 seconds, similar to Instagram's signup page. I am struggling to achieve this using the material-ui approach. Below is a snip ...

What is preventing access to the JSON data?

function loadResponse(filter) { $.ajax({ type: 'GET', url: 'path/to/example.json', dataType: 'json', cache: false, beforeSend: function () { console.log('load ...

"Encountered a Chrome RangeError: The call stack size limit was exceeded while utilizing jQuery's $

As part of my job, I am currently evaluating a web application that involves fetching a substantial amount of data from the server. The data is received as a JSON object using the $.ajax function. It contains numerous sub-objects which I convert into array ...

Focusing on the active element in Typescript

I am working on a section marked with the class 'concert-landing-synopsis' and I need to add a class to a different element when this section comes into focus during scrolling. Despite exploring various solutions, the focused variable always seem ...

Preventing Content Changes When Ajax Request Fails: Tips for Error Checking

I was struggling to find the right words for my question -- My issue involves a basic ajax request triggered by a checkbox that sends data to a database. I want to prevent the checkbox from changing if the ajax request fails. Currently, when the request ...

Avoiding quotations when inserting JSON data into MySQL table

I've encountered an issue with inserting a JSON string into a table using an insert query. Here is the problematic insert query: $insert_sql = 'INSERT INTO yun_postmeta (post_id, meta_key, meta_value) VALUES (5054, "_wc_free_gift_coupon_free ...

Relocating sprite graphic to designated location

I am currently immersed in creating a captivating fish animation. My fish sprite is dynamically moving around the canvas, adding a sense of life to the scene. However, my next goal is to introduce food items for the fishes to feast on within the canvas. Un ...

What is the most efficient way to print multiple JSON arrays simultaneously?

When looping through a database using an array, the following code snippet is used: $checkedProducts = $request->input('products'); $p = null; foreach($checkedProducts as $checkedProduct){ $p .= DB::table('products')->where( ...