Working with Key/Value pairs in an ArrayList using Javascript

I am currently expanding my knowledge on key/value arrays and object/properties.

I have a list of items stored in an array.

var itemList = [firstitem, seconditem];

How can I assign properties to each item in the itemList?

itemList[0].name = "pear";
itemList[0].value = "$5";

Am I doing this correctly?

var items = [ 
      { 
          "name": "pear",
          "value": "$2"
      }, {
          "name": "apple",
          "value": "$5"
      }];

Answer №1

If you're looking to initialize an array with predefined objects as items, one common way to do it is like this:

var items = [];
items[0] = {
    "name": "pear",
    "value": "$2"
};
items[1] = …

Alternatively, you could also do it like this:

var items = [];
items[0] = {};
items[0].name = "pear";
items[0].value = "$2";

items[1] = …

Answer №2

Check out this JS Fiddle link for a demonstration: http://jsfiddle.net/coolbhushans/3ubhnedm/

var items = [ 
      { 
          "name": "pear",
          "value": "$2"
      }, {
          "name": "apple",
          "value": "$5"
      }];

alert("1st name "+items[0].name +"\t second name " +items[1].name);
alert("1st value "+items[0].value+ "\t second value"+ items[1].value );

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

The select dropdown does not automatically refresh when the array value changes

I am facing an issue with a select dropdown that is populated by an array filled with data from the server response: myApp.controller('mController', function($scope, $routeParams, $http, contextRoot) { var dataObject = {} $scope.arr = [ ...

Refresh text displayed on a button with the help of setInterval

I need help updating the text on a button with the id fixed-button at regular intervals. Here is the code I am currently using: <script type="text/javascript"> $(function() { $('#fixed-button').setInterval(function() { ...

Encountering issues with JSON.Parse in JavaScript leads to errors

I'm encountering issues with JSON parsing in my code and I can't figure out the cause of it. I have a function that calls two ajax functions, one at the start and another in the success function. Everything seems to be working fine until I try to ...

Displaying an error message in a spreadsheet cell

Issue The problem arises when viewing the exported excel file where undefined is displayed. However, upon investigation, there are no empty array indexes causing this confusion. Solution Attempt const joinDate = new Date(obj.date); let snap = [ obj. ...

Accessing the value of a field using JavaScript/jQuery

Welcome to my page! I am working on obtaining the current Start and Finish date values. I plan to add a button for users to click, which will then retrieve all dates and display them somewhere on the page. But for now, I just need a way to access the date ...

The server experiences crashing issues when attempting to retrieve data from Mangodb for the second or third time

This is the code I have written in VS Code. const express=require("express"); const app= express(); const mongoose=require("mongoose"); const Listing=require("./models/listings"); const path=require("path"); const me ...

Can an additional height be added to the equalizer to increase its height?

Is it feasible to append an additional 35px to the height determined by Foundation Equalizer? For instance, if Equalizer computes a height of 350px, I would like to increase it by 35px. This means that the resultant style should be height: 385px; instead ...

Tips for organizing a JSON Array

In order to display my stats from a JSON file sorted by "verbruik", I have learned how to sort an array when it has just one piece of information like 1 = "12313", 3 = "2124". The entire JSON file is stored in a variable: for (var index in data) { va ...

What are the ideal scenarios for implementing React.Fragments?

Today I discovered React Fragments and their benefits. I learned that fragments are more efficient by reducing the number of tree nodes and improving cleanliness in the inspector. However, is there still a need to use div tags as containers in React compo ...

The animation came to a halt after a brief period

Here is the code I wrote. When the button is clicked, the 3 containers should start flashing indefinitely, but they stop after a while. I can't figure out why. Any ideas? <!DOCTYPE html> <html> <head> <title></title> & ...

JavaScript News Scroller for Horizontal Display

After searching through numerous websites, I have yet to find the ideal horizontal news scroller for my website. My specific requirements include: Must provide a smooth scrolling experience Scroll from right to left covering 100% width of the browser ...

The website must automatically adjust the size of all elements on the page, including images and fonts

I am currently facing an issue with the resizing of my web page when the user changes the window size or has a different screen resolution. I have created a jQuery function that triggers on resize or page load, which helps in scaling everything proportiona ...

Using the max-width property with Semantic UI Dropdown in ReactJS

I'm struggling to determine how to adjust the max-width of the Dropdown element in ReactJS. I attempted the following: .Menu Dropdown { max-width: 5rem !important; } Unfortunately, this did not work as expected. The dropdowns are taking up too m ...

Do JavaScript have dictionary functionality similar to Python?

I am trying to create a dictionary in JavaScript that looks something like this: I can't recall the exact syntax, but it was similar to: states_dictionary={ CT=[alex,harry], AK=[liza,alex], TX=[fred, harry] ........ } Does JavaScript support this ty ...

Sending data via an AJAX POST request in the request parameter

I have a question regarding the method of making a POST request in my code: $.ajax({ url :"/clientCredentials.json", type: "POST", data: { "clientEmail": email, "clientName":clientName, "orgName":orgName, "l ...

Mapping an object in ReactJS: The ultimate guide

When I fetch user information from an API, the data (object) that I receive looks something like this: { "id":"1111", "name":"abcd", "xyz":[ { "a":"a", "b":"b", "c":"c" ...

Having trouble with a 'Could not find a declaration file for module' error while using my JavaScript npm package?

I recently released a JavaScript npm package that is functioning properly. However, when importing it into another application, there always seems to be three dots in front of the name, along with an error message that reads: Could not find a declaration f ...

AddRegions does not function as expected

Basic code to initialize an App define(['marionette'],function (Marionette) { var MyApp = new Backbone.Marionette.Application(); MyApp.addInitializer(function(options) { // Add initialization logic here ...

AssertionError [ERR_ASSERTION]: The value of undefined is not equal to 390 in the GitLab

I'm a bit confused about the AssertionError [ERR_ASSERTION]: undefined == 390 in Gitlab. What I need is: The sumSalaries(obj) function, which should take an object obj as a parameter where the field names correspond to the employee's name and t ...

When utilizing Express and passport, an error occurs stating that req.isAuthenticated is undefined

After successfully setting up a backend express server in the past few hours, I decided to implement authorization by following a tutorial. The login functionality works perfectly, but when attempting to access /authrequired (a restricted page that require ...