Pratik açıdan, nesne sırası neredeyse her zaman korunur. Bir nesneye yeni bir öge eklerseniz, genellikle nesnenin sonuna eklenir.
var lunch = {
sandwich: 'turkey',
drink: 'soda',
chips: true
};
// This gets added after "lunch.chips" in the object
lunch.dessert = 'cookie';
Nesnedeki belirli bir dizinin belirli bir sırasına bir öge eklemek için şunları yapmamız gerekir:
- Yeni bir nesne oluştur.
- Döngü sayısını saymak için bir değişken ayarlanmalı (
nesnelerin bir yerel dizini olmadığından). - Orijinal nesne boyunca bir döngü yapılmalı.
- Dizin değişkeni, yeni anahtar / değer çiftini “eklemek istediğiniz pozisyona eşitse, bunu yeni nesneye ekle” şeklinde koşul oluşturulmalıdır.
- Eski anahtar / değer çiftlerini yeni nesneye iliştirmek gerekir.
- Her döngünün sonundaki dizin bir bir arttırılmalı.
Bununla başa çıkmak için küçük bir yardımcı işlev yazıldı.
var addToObject = function (obj, key, value, index) {
// Create a temp object and index variable
var temp = {};
var i = 0;
// Loop through the original object
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
// If the indexes match, add the new item
if (i === index && key && value) {
temp[key] = value;
}
// Add the current item in the loop to the temp obj
temp[prop] = obj[prop];
// Increase the count
i++;
}
}
// If no index, add to the end
if (!index && key && value) {
temp[key] = value;
}
return temp;
};
Kullanım Şekli
// Original object
var lunch = {
sandwich: 'turkey',
drink: 'soda',
chips: true
};
// Add to the end of the object
var lunchWithDessert = addToObject(lunch, 'dessert', 'cookie');
// Add between sandwich and drink
var lunchWithTopping = addToObject(lunch, 'topping', 'tomato', 1);
// Immutable copy of lunch
var lunchClone = addToObject(lunch);