Languages
[Edit]
EN

JavaScript - add new item to object at specific position

3 points
Created by:
Dirask Community
6930

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;
};

var user = { name: 'John', age: 30, hobby: 'football'};
var userExtended = insertProperty(user, 'email', 'johnh@email.com', 2);

console.log(JSON.stringify(user, null, 4));
console.log(JSON.stringify(userExtended, 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.

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