10 Tips and Tricks to Handle JavaScript Objects | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (173).NET Core  (29).NET MAUI  (206)Angular  (109)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (40)Black Friday Deal  (1)Blazor  (214)BoldSign  (14)DocIO  (24)Essential JS 2  (107)Essential Studio  (200)File Formats  (66)Flutter  (132)JavaScript  (220)Microsoft  (118)PDF  (81)Python  (1)React  (100)Streamlit  (1)Succinctly series  (131)Syncfusion  (911)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (50)Windows Forms  (61)WinUI  (68)WPF  (158)Xamarin  (161)XlsIO  (36)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (147)Chart  (130)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (624)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (40)Extensions  (22)File Manager  (6)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (504)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (386)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (588)What's new  (329)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
10 Tips and Tricks to Handle JavaScript Objects

10 Tips and Tricks to Handle JavaScript Objects

An object is the basic building block of programs in JavaScript, used in building classes and complex data, and as an integral part of object-oriented programming.

I have used JavaScript daily as a full-stack software developer for the last five-odd years. Objects of JavaScript have played a vital role.

In this article, I will share 10 tricks and tips you can use as a JavaScript developer to manipulate and work efficiently with JavaScript objects.

1. Creating an absolutely empty object

Creating empty objects seems like nothing but using {}. However, have you noticed that object methods such as proto and hasOwnProperty are still there when you create an object in such a method? This is because using {} will create an object that inherits from the Object class.

If you need to create an absolutely empty object, it’s better to use Object.create(null), which creates an object that is not inherited from anything and has no properties.

let vehical = Object.create(null);

// vehicle.__proto__ === "undefined"
// There are no object properties, keys, or methods until we add

Syncfusion JavaScript UI controls are the developers’ choice to build user-friendly web applications. You deserve them too.

2. Combining two objects using the spread operator

There are many scenarios where you must combine two or more data sets from different sources. In such cases, there are multiple ways to do this in JavaScript.

The most commonly used method is using Object.assign(). This method takes multiple parameters. The first one is the assigned object, and the rest of the parameters are the objects we need to combine.

const name = { id: '1234', name: 'Charuka'};
const university = { id: '1234', university: 'Harvard'};
const PersonalDetails = Object.assign({}, name, university);

console.log(PersonalDetails); 
// { id: '1234', name: 'Charuka', university: 'Harvard' }

However, without complicating things, you can use the spread operator to combine. You can spread any number of objects to combine them into a single object.

const PersonalDetails = { ...name, ...university };

console.log(PersonalDetails); 
// { id: '1234', name: 'Charuka', university: 'Harvard' }

One important fact to note is that duplicate keys will override those of the preceding objects in both methods.

3a. Getting the lists of keys and values from an object

During development, there are occasions when we need to obtain only keys or only values from an object. Both of the following built-in functions are pretty straightforward:

  • Object.keys(): used to get the list of keys.
  • Object.values(): used to get the list of values.
const vehicle = { brand: 'BWM', year: 2022, type: 'suv'};
//get keys
console.log(Object.keys(vehicle)); // [ 'brand', 'year', 'type' ]

//get values
console.log(Object.values(vehicle)); // [ 'BWM', 2022, 'suv' ]

3b. Using hasOwnProperty() to check an item

When using a for-in loop, checking a property of an object can be useful to avoid iterating through the properties from the object’s prototype. Instead of using an if-else block, here we can use Object.hasOwnProperty().

const vehicle = { brand: 'BWM', year: 2022, type: 'suv'};
for (var item in vehicle) {  
    if (vehicle.hasOwnProperty(item)) { 
        console.log(item);                 
    };  
};
// brand
// year
// type

Every property of the Syncfusion JavaScript controls is completely documented to make it easy to get started.

4. Using splice instead of delete

When using the delete method, an application will replace an item with undefined instead of removing it from the array. So it is better to use splice() to delete an item from an array.

Let’s see what happens when using delete.

var arrayItems = ['a' , 2 , 'b', '3', 'c', '4']; 
arrayItems.length; // returns 6 
delete arrayItems[2]; // returns true 
arrayItems.length; // returns 6
console.log(arrayItems); // [ 'a', 2, undefined, '3', 'c', '4' ]

When using splice(), the following occurs.

var arrayItems = ['a' , 2 , 'b', '3', 'c', '4']; 
arrayItems.length; // returns 6 
arrayItems.splice(2,1); // returns true 
arrayItems.length; // returns 5
console.log(arrayItems); // [ 'a', 2, '3', 'c', '4' ]

The delete method should be used to delete an object property.

5. Cloning an object correctly

Assume you have an object and need to copy it to change its value, but the original object should be unchanged. There are two methods of how you can do that.

The first method is to use Object.assign(), which copies values of all enumerable properties from one object to another.

var initialVehicle = { brand: 'BWM', year: 2022, type: 'suv'};
var secondaryVehicle = Object.assign({}, initialVehicle);
console.log(secondaryVehicle); // { brand: 'BWM', year: 2022, type: 'suv'};

The second method is to copy the object using JSON.parse().

var initialVehicle = { brand: 'BWM', year: 2022, type: 'suv'};
var secondaryVehicle = JSON.parse(JSON.stringify(initialVehicle));
console.log(secondaryVehicle); // { brand: 'BWM', year: 2022, type: 'suv'};

6. Selecting specific data from an object

There are a few methods to select keys from an object. The method you choose depends on what you want to do with the values. The following example shows an organized way of selecting data from an object. 

Here, you can select the keys you need and pull them into a new object.

const selectObj = (obj, items) => { 
  return items.reduce((result, item) => {
    result[item] = obj[item]; 
    return result;
  }, {});
};
const vehicle = { brand: 'BWM', year: 2022, type: 'suv'};
const selected = selectObj(vehicle, ['brand', 'type']);
console.log(selected); // { brand: 'BWM', type: 'suv' }

To make it easy for developers to include Syncfusion JavaScript controls in their projects, we have shared some working ones.

7. Removing keys from an object

Sometimes it is necessary to remove specific keys and their values from an object.

This might be necessary for a scenario where you are building an API and want to remove sensitive data.

The most suitable method is to write a reusable remove method that takes an object and a list of keys to be removed as inputs. You can then loop through each key to be removed and delete it from the object.

const remove = (object, removeList = []) => {
  const result = { ...object };
  removeList.forEach((item) => {
    delete result[item];
  });
  return result;
}

const vehicle = { brand: 'BWM', year: 2022, type: 'suv'}

const itemRemoved = remove(vehicle, ['year']);
console.log(itemRemoved); // Result { brand: 'BWM', type: 'suv' }

8. Pulling object data into an array

There are scenarios where you need to pull your object data into an array, such as a dropdown menu. You can use the Object.entries() function, which takes an object as its first argument and returns an array.

The returned object is an array of an array. The inner arrays will have two values: the first is the key, and the second is the value.

const vehicle = { brand: 'BWM', year: 2022, type: 'suv'}
console.log(Object.entries(vehicle)); 
// [ [ 'brand', 'BWM' ], [ 'year', 2022 ], [ 'type', 'suv' ] ]

9. Looping through a JavaScript object

There are several methods in JavaScript that can be used to loop through an object. I will compare two of the best methods I use.

The first method is to use Object.entries(), a function that avoids looking up each value in the original object.

const vehicle = { brand: 'BWM', year: 2022, type: 'suv'}
Object.entries(vehicle).forEach(
    ([key, value]) => console.log(key, value)
);
// brand BWM
// year 2022
// type suv

As a much better and clearer method, you can use object destructuring with Object.entries().

const vehicle = { brand: 'BWM', year: 2022, type: 'suv'}
for (const [key, value] of Object.entries(vehicle)) {
    console.log(key, value);
}
// brand BWM
// year 2022
// type suv

Syncfusion JavaScript controls allow you to build powerful line-of-business applications.

10. Conditionally adding attributes to objects

Usually, developers use an if-else condition as a much longer method to add a new element to an object conditionally. However, the simplest way is to use object destructuring and the spread operator.

const type = { type: 'suv' };
const vehicle = {
  brand: 'BMW',
  year: 2022,
  ...(!type ? {} : type)
}
console.log(vehicle); //{ brand: 'BMW', year: 2022, type: 'suv' }

Likewise, using different conditions, you can add as many elements as you like to an object.

Conclusion

Like any other programming language, JavaScript has many tricks to handle objects, letting us write our programs more simply and beautifully. This article discussed 10 of the tips and tricks I use most when dealing with objects.

I hope you found this article helpful. Thank you for reading.

Syncfusion’s Essential JS 2 is the only suite you will need to build an app. It contains over 65 high-performance, lightweight, modular, and responsive UI components in a single package. Download a free trial to evaluate them today.

Please let us know if you have any questions in the comments section below. You may also get in touch with us via our support forum, support portal, or feedback portal. We are delighted to assist you!

Related blogs

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed