简体   繁体   中英

How do I insert a key value pair at a specific point in a key/value array in jquery/javascript?

Hope someone can help in jquery if I have a key value array object

    var myArray= {};
    myArray['key1'] = 'value1';
    myArray['key2'] = 'value2';
    myArray['key3'] = 'value3';
    myArray['key5'] = 'value5';
    myArray['key6'] = 'value6';

how would I insert another key value pair at a specific point? eg myArray['key4'] = 'value4'; between (or after) key2 and (or before) key3?

Thank you

There is no guaranteed order in ECMAscript Objects , hence, there is no way to insert a new key/value pair at a certain point.

Use an Array instead.

var arr = ['value1', 'value2', 'value3', 'value4', 'value5', 'value6'];

arr.splice(2, 0, 'new value');

console.log( arr ); // ['value1', 'value2', 'new value' 'value3', 'value4', 'value5', 'value6'];

What you have is an object ( {} ), not an array ( [] ). Keys in objects don't have a guaranteed ordering, so you can't insert one at a specific point; they're just properties of that object.

Thanks for the input. I was hoping their was an equivalent to splice for objects that I had missed. Obviously not so I resorted to good old map and rebuild.

function objectInsertafterkey(object, newKey, newVal, insertAfterkey){
newObject={};
$.map(object, function(value, key) {    
if(key == insertAfterkey){
newObject[key] = value;
newObject[newKey] = newVal;
}
else
{
newObject[key] = value;
}
});
return newObject;
}

If their is a better way to insert into objects feel free to let me know.

do like this,use object:

 var myArray = {key1: value1, key2: value2};

add new:

myArray.key3 = "value3";

This may help you:

the arr.splice will add a new value to existing array

http://www.w3schools.com/jsref/jsref_splice.asp

As jAndy says, if you want a specific order, use arrays.

Alternatively, you can sort the keys before use if they have sortable names (like in your example).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM