EN
JavaScript - add new item to object at specific position
3
points
In this article, we would like to show you how to add a new item to object at a specific position in JavaScript.
Runnable example:
// ONLINE-RUNNER:browser;
function insertProperty(obj, key, value, position) {
var result = {};
var counter = 0;
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
if (counter === position) {
result[key] = value;
}
result[prop] = obj[prop];
counter++;
}
}
if (!(key in result)) {
result[key] = value;
}
return result;
};
// Usage example:
var oldUser = { name: 'John', age: 30, hobby: 'football'};
var newUser = insertProperty(oldUser, 'email', 'johnh@email.com', 2); // position from 0
console.log('Old user: ' + JSON.stringify(oldUser, null, 4));
console.log('New user: ' + JSON.stringify(newUser, null, 4));
Explanation how it works:
- To add a new item to an object we need to create a new empty object and a
counter
for object position since objects don't have an index. - We loop through the original object until the
counter
value equals theposition
we want to insert the newkey
/value
pair. - When it does, we push the new
key
/value
pair to the new object and loop through the rest of the original object's items.
Note:
This approach is suboptimal because it needs to rewrite the entire object.