The array becomes empty after a value has been assigned to it

I am currently working with a variable containing JSON data.

var blogData = [
                 {
                   "blogTitle":"Bangladesh",
                   "imagePath":"/img/blog/bangladesh.jpg"
                 },{
                   "blogTitle":"India",
                   "imagePath":"/img/blog/india.jpg"
                 }
               ]

My goal is to create a new array called titleFilter as follows:

var titleFilter = [
                    Bangladesh : "/img/blog/bangladesh.jpg",
                    India : "/img/blog/india.jpg"
                  ]

To achieve this, I have attempted the following code:

var titleFilter = [];
        for (var i = 0; i < blogData.length; i++) {
            titleFilter[blogData[i].blogTitle] = blogData[i].imagePath;   
        }

However, I am encountering an issue where the titleFilter array appears as:

var titleFilter = [
                        Bangladesh : "",
                        India : ""
                  ]

If anyone could provide assistance with this problem, it would be greatly appreciated.

Answer №1

Give this a try:

const travelDestinations = [
                 {
                   "destination":"Thailand",
                   "image":"/img/travel/thailand.jpg"
                 },{
                   "destination":"Greece",
                   "image":"/img/travel/greece.jpg"
                 }
               ];
               
const destinationImages = travelDestinations.reduce((acc, place)=> (acc[place.destination] = place.image , acc),{});

console.log(destinationImages);

Answer №2

If you're uncertain about your search, consider utilizing a map in this manner to accomplish it.

let items = new Object(); // or let items = {};
items[blogData[index].title] = blogData[index].url;

Answer №3

 const postList = [
                {
                  "postTitle":"Summer Recipes",
                  "imagePath":"/img/posts/summer-recipes.jpg"
                },
                {
                 "postTitle":"DIY Crafts",
                 "imagePath":"/img/posts/diy-crafts.jpg"
                }
              ]

const titleFilter = {}
postList.forEach( post => titleFilter[post.postTitle] = post.imagePath ) 

Implement this code snippet to populate the titleFilter with the necessary data.

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

Navigating through sibling elements can be accomplished by using various methods in

Can someone help me figure out how to assign unique IDs to 6 different Div elements as I step through them? The code snippet below is not working as expected, giving all Divs the same ID. What is the correct way to accomplish this task? $('#main-slid ...

The most effective method for adding a new key/value pair to a nested object

Currently working with React and attempting to add a new key-value pair to an object. I have an if check that verifies a condition, and if it is met, I want to include the key 'author'. if (field.component === 'Author') { this.pro ...

Create a variable and set it equal to the value of a form

I'm having trouble setting a value to a hidden form field that needs to come from a query string parameter. The function that extracts the query string parameter is working properly, but the function that assigns this variable to the hidden form field ...

Setting the response type to text in Angular 6 when making an http call

Attempting to send an HTTP request to the Spring REST API, which returns a string value ('success' or 'fail'). However, I am uncertain of how to specify the response type as a string value when making the call to the API. The error mess ...

Value comparison displayed in text boxes

Having two textboxes and a script to compare their values can sometimes result in unexpected behavior. For instance, when the value in Textbox2 comes from the database and it happens to be 0, it can cause issues. One possible solution is to allow Textbox1 ...

What is causing this issue that is preventing me from async rendering Vue components?

I am new to working with Vue and I am attempting to lazy load a Component. However, I encountered an error that seems to be related to a syntax issue. Below is the code snippet: <template> <div class="container"> <h1>Asy ...

Issue with parsing JSONP using jQuery's AJAX request

I am encountering an issue with a jQuery ajax request that I have set up. Here is the code: jQuery.ajax({ url: serverAddress+'php/product.php', type: 'GET', jsonpCallback: "callback7", dataType: 'jsonp', d ...

What is the process for incorporating the !important declaration into a CSS-in-JS (JSS) class attribute?

I'm currently exploring the use of CSS-in-JS classes from this specific response in conjunction with a Material UI component within my React project. In order to override the CSS set by Bootstrap, I've decided to utilize the !important modifier. ...

The server is constantly sending data through Server Sent Events

I am currently a student working on a project involving a social trading platform. I am looking to incorporate a notification system and believe that SSE would be a great fit for this purpose. However, I am facing an issue where my SSE code is sending data ...

The ajax method for loading an xml file results in displaying the undefined message

When attempting to fetch content from an xml file using ajax, the page initially displays "undefined". However, upon refreshing the page, the content loads successfully. Take a look at my code snippet below: $.ajax({ type: "GET", url: "xm ...

How to handle a JSON file that references a deleted class?

Recently, I found myself in a situation where I had to remove a class that was utilized by numerous JSON documents. However, as a result of this removal, deserialization is now failing because the referenced class no longer exists. The error message being ...

What methods can I utilize from Google Maps within Vuex's createStore()?

Currently, I am in the process of configuring my Vuex store to hold an array of Marker objects from the Google Maps Javascript API. Here is a snippet of how my createStore function appears: import { createStore } from "vuex"; export default ...

Transforming AngularJS $http POST requests into GET requests

I came across a scenario where I needed to update the logo path in my application. So, I defined a route like this: Route::post('/updateLogo', 'CaptivePortalController@updateLogo'); After defining the route, I made a POST request as s ...

Utilize the most recent impacted information stored within an object

When I return this list object, it includes: return ({ name: data.name, request: { method: methodLine[index].method.toUpperCase(), header: data.request.header, description: data.request.description, }, response: [ { ...

Clicking on an item will now automatically remove it from the selection, rather than requiring you to click on a specific

Is there a way to customize the design of select2 items in a multi-select box so that users can easily remove selected items by clicking anywhere on the button, rather than just the small "cross" icon on the left-hand side? Refer to the image; instead of n ...

Mirroring an array in Java

I'm a beginner in Java and I have been given a task to develop an application. I encountered an issue that I can't seem to overcome. The problem involves updating an array element using reflection (the application selects a public array to updat ...

What could be causing the promise in Angular 8 to return an undefined value, even though it was correctly logged just before it was resolved?

MODIFY I checked to see if the script is entering the addHousehold() if condition here: addHouseholdPromise.then((res) => { console.log("Promise HH: "+res) if (res != "add_hh_fail") { console.log("success: "+res) return res ...

Enable/disable specific dates in datepicker depending on dropdown selection

Struggling with disabling specific days of the week in the jQuery datepicker based on a selected dropdown option. Provided below is the snippet of my HTML and JavaScript code: <script> $("#dates").datepicker({ minDate: 0 }); </sc ...

ajax request sends data to php file, which then processes the data and sends it back using $_POST

Currently, I am in the process of developing a budget management application using a combination of HTML, Javascript, and PHP. The main objective is to allow users to input data into a database through a form interface. To achieve this functionality, I hav ...

Expanding upon passing arguments in JavaScript

function NewModel(client, collection) { this.client = client; this.collection = collection; }; NewModel.prototype = { constructor: NewModel, connectClient: function(callback) { this.client.open(callback); }, getSpecificCollection: ...