javascript push key value

arrays, javascript, jquery, key-value, php

Solution

Javascript key/value pair support in Object, not in Array

Insert Element:

var arr= [1,2,3],
    result = {};

for(var key in arr) {
   result[key] = arr[key]; // in this case key will be 0,1,2 i.e index of array element
}

Check that a key exists:

function checking(k, v) {
  if(result.k != null || result.k !=  undefined) {
    // do something
  }
}

According to your function:

var err = {}; // not array, should be object
function check(k,v) {
  err[k] = v; // or err.k = v;
}

More on insert:

var x = [];

x.some = 'some'; // OK; arrays are objects
x['some'] = 'some'; // exactly the same

Get value:

x.home; // give 'some'
x['home']; // give 'some'

Count length:

If you want to get length of an array you have to use `.length`.

For example:

x.length; // will return 1

And if you want to count the length of an Object:

var obj = {a: 'XYZ', b: 'PQR'};

Object.keys(obj).length; // will return 2

To Delete item:

if you want to remove an item from an Object:

delete obj[key];

to delete an item from an array:

delete arr[index]; // index is position of the element within array

also to remove array element you can do

arr.splice(0,2); // splice(index, howmany, [item1, item2, ...., itemx])
                 // in this example from start 2 items will delete

Problem

In my mind I want to push a key-value on array. Say for example in PHP this is done like this: ``` $err = array(); function check($k,$v) { $err[$k] = $v; } ``` How is this done exactly in JavaScript/jQuery?

Original source

Related problems