Fastest way to check if an object is empty
October 27, 2021
1 min
Given an object, we would like to insert a property and value at spcific position.
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.
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
}
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
}
addToObject(obj, '__CUSTOM_2', 'VALUE')addToObject(obj, '__CUSTOM_2', 'VALUE', 4)Quick Links
Books Authored by Me