Changing an object into an array for saving and transforming it back to an array for usage in JavaScript

I am dealing with a unique situation where I have an object created from dynamic checkboxes in Angular. The structure of the object looks like this:

{"United States":true,"Canada":true,"Australia":false} 

While this format works well for storing values, I need to convert it into an array in order to perform database searches on the country values and save it to MongoDB/Mongoose as follows:

["United States":true,"Canada":true,"Australia":false] 

After performing the database operation, I would then need to convert it back to the original object type for application use.

Can anyone suggest the simplest method to achieve this conversion process?

Answer №1

If I were to fill in the missing values, they might look like this:

"string", boolean, "string", boolean, "string", boolean

Here's how you can achieve this:

// Begin with the object...
var countryObject = {"United States":true,"Canada":true,"Australia":false};

// ... simplify it for explanation purposes:
var countryObject = {"A":true,"B":true,"C":false};

var compact = [];
for(var prop in countryObject){
    compact.push( prop );
    compact.push( countryObject[prop] );
}

// The 'compact' array now contains interpolated values:
// ["A", true, "B", false, "C", true];

Just so you know, you can efficiently search the array by locating the index of the string value and then adding 1 to retrieve its corresponding boolean value:

var foundIndex = compact.indexOf("B");
var result;
if(foundIndex > -1){
    result = countryArray[foundIndex + 1];
}

To reassemble the pieces:

var compact = ["A", true, "B", false, "C", true];
var countryObject = {};
for(var i=0; i<compact.length; i+= 2){
    countryObject[compact[i]] = compact[i+1];
}

Answer №2

Your request seems a bit confusing because the array shown is actually an associative array with key-value pairs, which in JavaScript is considered an object.

If you want to create an array with key-value pairs, you can do it like this:

var sampleArray = [];
sampleArray['example'] = 1;

Just keep in mind that when you add key-value pairs to an array in JavaScript, you are essentially treating the array as an 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

FullCalendar Angular 10 not displaying correct initial view

I am currently using Angular 10 along with FullCalendar version 5.3.1., and I am facing an issue where I cannot set the initial view of FullCalendar to day view. It seems to be stuck on the dayGridMonth view by default. Below is the HTML snippet: <full ...

Transforming CSV files into JSON format using d3.js

I'm encountering an issue when attempting to convert CSV to JSON. The following is the snippet of code I am using for the conversion: d3.csv("http://localhost:8080/Sample/flight.csv", function(flights) { //alert(flights); ...

Deciphering the intricacies of the http request

I encountered an issue while trying to send a POST request using jQuery AJAX. Upon making the request, I received the following error: XMLHttpRequest cannot load. Response for preflight has invalid HTTP status code 403 Now, I am unsure if the mistake i ...

Activeadmin prefers angular js routes over rails routes

My current application utilizes Rails 3.2.17 and AngularJS. I am interested in integrating Activeadmin into the existing setup. To achieve this integration, I followed the guidelines outlined in a blog post on Activeadmin by Ryan Bates. Here are the steps ...

When would this be required within JavaScript or Angular?

Being new to JavaScript, I have come across information stating that the value of this changes based on how a function is invoked. However, I am confused about when it is necessary to use this and when it is not. Some code examples I've seen utilize t ...

Chrome on IOS: Experiencing screen freezing while scrolling

1) I'm working with Material UI in React JS. I have added a simple scrollable code, but when I reach the bottom of the screen/scroll, it freezes. 2) I also tried it with a simple HTML page and it worked correctly. <div style={{ ...

"Exploring the world of AngularJS Datepicker alongside the power

My desire is to have a calendar that displays only the option of selecting a month and year, with the format being displayed as "yyyy-mm". Once the month and year are selected, I need it to update the ng-model variable value in the specified format. I&apos ...

increase the selected date in an Angular datepicker by 10 days

I have a datepicker value in the following format: `Fri Mar 01 2021 00:00:00 GMT+0530 (India Standard Time)` My goal is to add 60 days to this date. After performing the addition, the updated value appears as: `Fri Apr 29 2021 00:00:00 GMT+0530 (India St ...

Searching Firestore arrays for objects based on one of two fields

Within my document, I am working with the following array: I have a SizeFilterComponent that emits a BaseFilter object when a size is selected. Multiple sizes can be selected. Here is the method handling this logic: selectionChange($event){ let array ...

Determine if a certain value is present in a JSON data structure

Exploring the depths of NodeJS, I am utilizing a JSON Object for user validation. JSON content (users.json): { "users": [{ "fname": "Robert", "lname": "Downey Jr.", "password": "ironman" }, { "fname": "Chris", ...

How to access a variable from within a Phonegap DB function and return it outside of the

I'm struggling with a phonegap db JavaScript script that isn't returning the final string variable "feeds" outside the function. It's currently showing as "undefined". I need help making the necessary changes to properly return the "feeds" v ...

Create a new button dynamically within an HTML table row using pure JavaScript programming techniques

Currently, I am retrieving JSON data from an API and then displaying this data in an HTML table using plain JavaScript. My goal is to dynamically add a button at the end of each row for additional functionality, but so far, I have been unable to figure out ...

When using the .append method in jQuery, the JSON array only displays the last value of the array when iterating through it with

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Displaying Array Data in Table Using Javascript</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">& ...

Combining Django's CSRF token with AngularJS

I currently have Django running on an Apache server with mod_wsgi, and an AngularJS app being served directly by Apache rather than through Django. My goal is to make POST calls to the Django server that is utilizing rest_framework, but I am encountering d ...

Removing CSS from an HTML document using Gulp

My Web App is built using Angular and I encountered an issue with Gulp. Every time I add a new custom CSS line to my HTML file and run Gulp, it automatically removes that line from the file. <!--MATERILIZE CORE CSS--> <link h ...

Retrieve targeted information from the Coin Market Cap API by extracting specific data values using an array

I am looking to retrieve the symbol and other details using the "name" from my array. $.getJSON("//api.coinmarketcap.com/v1/ticker/?limit=0", function(data) { var crypto = [ "Ethereum", "Ripple", "Tron", ]; // used for arr ...

What is the best way to sort a combination of numbers and text strings?

Within my table, I have column names enclosed in <th> tags and only numerical values inside <td> tags. When the user clicks on a <th> tag, the sorting algorithm organizes the values in ascending or descending order. .sortElements(function ...

Code snippet for fetching JavaScript file using Angular's caching mechanism

Currently in my project, I am utilizing $.getScript to dynamically load specific sections of code. Here's a snippet of how it looks: var mainJs = "/main.js"; $.getScript( mainJs ) .then(function () { console.log("main.js loaded"); }); ...

How to handle Component binding change events in AngularJS

I have developed a component in AngularJS that displays data. However, when the customer binding changes, I need to call a service in the component controller, but it is not updating. Below is the code snippet: In my Test1.html file: <tab-customer tit ...

Tips for adding a CSS marker to the Videogular timeline at a designated time

My HTML player application allows users to search for a term and then displays the results along with the time when those words appear. By clicking on a specific sentence, the HTML player will start playing from that location. However, I would like to enha ...