Languages
[Edit]
EN

JavaScript - add new item to object at specific position

3 points
Created by:
Vanessa-Drake
718

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:

  1. 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.
  2. We loop through the original object until the counter value equals the position we want to insert the new key/value pair.
  3. 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.

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join