Javascript push ассоциативный массив

JavaScript associative array push | Example code

Just use the Array push() method to push values in JavaScript associative array.

If you want named properties, don’t use an Array. Arrays are for ordered data structures accessed by index.

Use an Object instead.

You can use an object as a key-value store, where the keys are strings (or symbols) and the values can be of any type, including arrays. Here’s an example of pushing values into an array stored in an object:

// Create an object const myObject = <>; // Initialize an array as a value myObject['myArray'] = []; // Push values into the array myObject['myArray'].push('value1'); myObject['myArray'].push('value2'); console.log(myObject['myArray']); // Output: ['value1', 'value2']

JavaScript associative array push

       

JavaScript associative array push

Using Maps: Maps are a built-in data structure in JavaScript that allows you to associate values with keys. Unlike objects, Map keys can be of any type. Here’s an example of using a Map to push values into an array:

// Create a new Map const myMap = new Map(); // Initialize an array as a value myMap.set('myArray', []); // Push values into the array myMap.get('myArray').push('value1'); myMap.get('myArray').push('value2'); console.log(myMap.get('myArray')); // Output: ['value1', 'value2'] 

Array push in JavasSript associative Array

var markedDates = []; var markedDate = <>; markedDate['dates'] = []; markedDate['dates'].push(); markedDate['dates'].push(); markedDate['styleClass'] = 'test'; markedDates.push(markedDate); console.log(markedDates);

Do comment if you have any doubts or suggestions on this Js Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Источник

push JS в ассоциативный массив

Для программирования нужно уметь думать и решать подобные задачи. Вам надо научиться думать и тогда не будете такие вопросы задавать. Или вы думаете если раньше вам помогали, то всегда будут помогать? Как вы видите людям это уже надоело.

Я хочу пересобрать массив но не понимаю как это сделать в JS Я хочу создать новый многомерный массив где 1. Дата 2. ФИО 3. territory_id (в нем уже данные available_slots) Вот как я пытаюсь это сделать

if (Object.keys(json[0]['shedule']).length !== 0) let dayArray = []; 
$.each(json[0]['shedule'], function (key, value) let countSlots = value['available_slots'].length;
for (let i = 0; i < countSlots; i++) let data = new Date(value['available_slots'][i]);
let dataFormat = data.getFullYear() +''+ ("0" + (data.getMonth() + 1)).slice(-2) +''+ data.getDate();
dayArray[dataFormat] = [value['staff_name']];
>
>);

В итоге получил Я не понимаю почему в цикле можно сделать так

dayArray[dataFormat][value['staff_name']]

Две мысли. 1. Формально в JS массивы могут быть только с числовыми ключами. Если ключ — строка, то это объект.В php можно в массиве оба варианта ключей использовать.
Видите, у вас в консоли параметр length равен 20220431 — т.е. у вас там дофига пустых значений в массиве, что, насколько я помню, не очень хорошо для производительности. 2. Конкретно по вашему коду, вам «повезло», что дата преобразуется в число и можно это число использовать как индекс у массива. Когда вы пытаетесь записать сразу «внутрь» массива, вы по сути пытаетесь записать сразу внутрь несуществующего объекта. Т.е. сначала надо бы сделать

dayArray[dataFormat][value['staff_name']]

В целом, мой непрошенный совет — работайте и с объектами, там можно ключи делать строковые. Т.е. у вас будет

dayArray[dataFormat] = <>; dayArray[dataFormat][value['staff_name']] = []

dayArray[dataFormat][value[‘staff_name’]].push(

Т.е. у вас будет объект, у которого будут ключами даты (причем можно в удобном вам формате), значения будут тоже объектами, а вот в этих объектах значения будут уже массивами. Если я правильно понял структуру, которая вам нужна.

ArbNet #:
Для программирования нужно уметь думать и решать подобные задачи. Вам надо научиться думать и тогда не будете такие вопросы задавать. Или вы думаете если раньше вам помогали, то всегда будут помогать? Как вы видите людям это уже надоело.

Источник

Push Key-Value Pair Into an Array Using JavaScript

Push Key-Value Pair Into an Array Using JavaScript

  1. Push Key-Value Pair Into an Array Using JavaScript
  2. Use map() to Push Key-Value Pair Into an Array in JavaScript
  3. Use reduce() to Push Key-Value Pair Into an Array in JavaScript
  4. Use jQuery to Push Key-Value Pair Into an Array in JavaScript

This article discusses how to push key-value pairs into an array using JavaScript. We can use jQuery and arrow functions with map() and reduce() methods.

The goal can also be accomplished without using any built-in method (discussed later in this article).

Push Key-Value Pair Into an Array Using JavaScript

Let’s start without using build-in methods and functions. In the following code, we have an array named arr1 containing two elements, left and top .

We declare another array and an object named arr2 and obj , respectively.

Write a for loop that gets executed until arr1.length-1 . On each iteration, we use bracket notation to create key-value pair for obj .

Once it is done, we use the push() method to insert obj into arr2 and print it on the console.

var arr1 = ['left', 'top'], arr2 = []; var obj = <>;  for (i = 0; i  arr1.length; i++)   obj[arr1[i]] = 0; >  arr2.push(obj); console.log(arr2); 

Now, let’s move to built-in functions and methods to push key-value pairs into arr2 .

Use map() to Push Key-Value Pair Into an Array in JavaScript

The ECMAScript6 (ES6) introduces the arrow functions that let us write the function more concisely. We can only use this function if the function has only one statement.

The map() method makes a new array by calling a function once for every array’s element. It does not modify the original array and run for empty elements.

var arr1 = ['left', 'top']; const arr2 = arr1.map(value => (: 0>)); console.log(arr2); 

You may have observed that we can add two objects with the same data. Each object has one property in the above output.

Use reduce() to Push Key-Value Pair Into an Array in JavaScript

The reducer function got executed by the reduce() method. It returns only one value, and that is the accumulated answer of the function.

Like the map() method, the reduce() method does not update the original array and runs the function for the array’s empty elements.

var arr1 = ['left', 'top']; const arr2 = arr1.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), <>); console.log(arr2); 

Use jQuery to Push Key-Value Pair Into an Array in JavaScript

Assume that you want a key-value pair of one object with two properties ( left , top ) in the arr2 array. Let’s do it using jQuery.

var arr1 = ['left','top'], arr2 = []; var obj = <>;  $.each(arr1,function(index, value)  obj[value] = 0; >);  arr2.push(obj); console.log(arr2); 

What if we have two arrays named keys and values . We want to take all elements from keys and values and push them in a third array.

See the following example.

var keys = ['ID','FirstName', 'LastName', 'Gender'],  values = [1, 'Mehvish', 'Ashiq', 'Female'],  arr = []; var obj = <>;  for(i = 0 ; i  keys.length && i  values.length ; i++)  objJavascript push ассоциативный массив] = values[i]; > arr.push(obj); console.log(arr); 
[  FirstName: "Mehvish",  Gender: "Female",  ID: 1,  LastName: "Ashiq" >] 

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

Related Article — JavaScript Array

Источник

Читайте также:  Python decimal to bytes
Оцените статью