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:
xxxxxxxxxx
1
function insertProperty(obj, key, value, position) {
2
var result = {};
3
var counter = 0;
4
for (var prop in obj) {
5
if (obj.hasOwnProperty(prop)) {
6
if (counter === position) {
7
result[key] = value;
8
}
9
result[prop] = obj[prop];
10
counter++;
11
}
12
}
13
if (!(key in result)) {
14
result[key] = value;
15
}
16
return result;
17
};
18
19
20
// Usage example:
21
22
var oldUser = { name: 'John', age: 30, hobby: 'football'};
23
var newUser = insertProperty(oldUser, 'email', 'johnh@email.com', 2); // position from 0
24
25
console.log('Old user: ' + JSON.stringify(oldUser, null, 4));
26
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.