About MePublicationsContact

Insert Property and values at specific position in an Object in JavaScript

By Suresh Kumar Mukhiya
Published in Frontend Cheetseat
December 26, 2021
1 min read

Problem:

Given an object, we would like to insert a property and value at spcific position.

Input:

const testObject = {
  id: 42,
  __EMPTY: 'EUROPRIS AS',
  __EMPTY_1: 'EUROPRIS AS',
  Apple: 'Frukt',
  __EMPTY_2: 7270424,
  Eiendomsrapport: 43831,
  __EMPTY_3: 44197,
  __EMPTY_4: 'MASKINFORSIKRING',
  __EMPTY_5: 'STASJ.ELEKTR.UTSTYR 1.RISIKO',
  __EMPTY_6: '256 EUROPRIS BUTIKKER',
  __EMPTY_7: '',
  __EMPTY_8: 76800000,
  __EMPTY_9: 27648,
  __EMPTY_10: 0
}

And say, we want to insert a property and value __CUSTOM_1: 33434 between __EMPTY_7 and `__EMPTY_8.

Expected Output:

const testObject = {
    "id": 42,
    "__EMPTY": "EUROPRIS AS",
    "__EMPTY_1": "EUROPRIS AS",
    "Apple": 'Frukt',
    "__EMPTY_2": 7270424,
    "Eiendomsrapport": 43831,
    "__EMPTY_3": 44197,
    "__EMPTY_4": "MASKINFORSIKRING",
    "__EMPTY_5": "STASJ.ELEKTR.UTSTYR 1.RISIKO",
    "__EMPTY_6": "256 EUROPRIS BUTIKKER",
    "__EMPTY_7": "",
    "__CUSTOM_1": 33434
    "__EMPTY_8": 76800000,
    "__EMPTY_9": 27648,
    "__EMPTY_10": 0
}

Solution:

const 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 (Object.prototype.hasOwnProperty.call(obj, 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) {
    Object.assign(temp, { [key]: value })
  }

  return temp
}

Usage

  • To insert an item to the end the object, addToObject(obj, '__CUSTOM_2', 'VALUE')
  • To insert an item at a specific position, pass the index addToObject(obj, '__CUSTOM_2', 'VALUE', 4)

Tags

ObjectJavaScript
Previous Article
Autoimport React using Webpack’s ProvidePlugin
Suresh Kumar Mukhiya

Suresh Kumar Mukhiya

Software Engineer

Topics

Artificial Intelligence
Frontend Cheetseat
My Philosophy
Paper Review
Research Methods
Software Architecture

Related Posts

Fastest way to check if an object is empty
October 27, 2021
1 min
© 2022, All Rights Reserved.

Quick Links

PublicationsAbout meContact Me

Social Media