Home javascript Analog Push () for objects

Analog Push () for objects

Author

Date

Category

Hello everyone. Today I encountered such a problem. I needed to add elements into an associative array. On JavaScript there is no associative arrays, so I did as an object. Now I can not find the analogue of the Push () function. Tell me if anyone knows. Thank you.


Answer 1, Authority 100%

Do you want the keys to be ordinary incremental numbers?

Not really. The first key is some word, the second key is numbers.

OBJ ['KEY'] = [];
OBJ ['Key']. Push ('Value1');
OBJ ['Key']. Push ('Value2');
OBJ ['KEY'] [0]; // 'Value1'
OBJ ['KEY'] [1]; // 'Value2'

Answer 2, Authority 71%

Through the cycle, it is not difficult to fill the object by type key – value from the array.

var datarow = ['string1', 'string2', 'string1'];
var OBJ = {};
$ (datarow) .each (Function (E, I) {
  OBJ [E] = I;
});
// E - Cell index in the array.
// I - Cell content, there can be anything.

At the output, we get:

object {0: "String1", 1: "String2", 2: "String1"}

or so possible:

var datarow = [{name: 'john', data: "text1"}, {name: 'Mark' , Data: "Text2"}, {name: 'Tom', Data: "Text3"}];
var OBJ = {};
$ (datarow) .each (Function (E, I) {
  OBJ [i.name] = i.data;
});

at the output will be:

object {john: "text1", mark: "text2", Tom: "text3"}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions