• Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

How to add a new object (key-value pair) to an array in javascript?

I have an array as :

How should I add a new pair {'id':5} to the array?

Marc Audet's user avatar

  • Thanks @NDM for comment. I tried some code on jsfiddle and it is working (with items.push({'id':5})....) But when I use the same code, the browser shows {{item.id}} instead of showing the updated value of items (I am using angularjs btw). I don't know why is this happening. –  exAres Commented Sep 23, 2013 at 8:33
  • possible duplicate of Add new value to an existing array in JavaScript –  chryss Commented Sep 23, 2013 at 16:12
  • The OP is creating an array of objects, not an array of values. –  Marc Audet Commented Sep 23, 2013 at 16:23
  • Possible duplicate of Appending to array –  adeady Commented Dec 15, 2015 at 15:32

5 Answers 5

Use .push :

CodingIntrigue's user avatar

  • 4 how can i add it at particular position in the array? say add it at index 3 –  separ1 Commented Feb 20, 2017 at 11:09
  • @separ1 arr[2] = "name"; –  user7270134 Commented Nov 18, 2019 at 12:52
  • 1 @Shmulik That will replace position 2 rather than add it there. You actually want arr.splice(3, 0, {'id': 3}) –  Nick Murphy Commented Dec 7, 2019 at 20:48

.push() will add elements to the end of an array.

Use .unshift() if need to add some element to the beginning of array i.e:

items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}]; items.unshift({'id': 0}); console.log(items);

And use .splice() in case you want to add object at a particular index i.e:

items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}]; items.splice(2, 0, {'id': 2.5}); console.log(items);

Mohammad Usman's user avatar

  • May I know how to add [{'id': 1,'newId': 'x' }, {'id': 2,'newId': 'y'}, {'id': 3,'newId': 'z'}] ? –  KcH Commented May 12, 2020 at 12:07
  • @Codenewbie Sorry, I didn't get your question. It would be great if you please create some working example with expected sample data and expected output. –  Mohammad Usman Commented May 12, 2020 at 13:22
  • sure , i would ask –  KcH Commented May 12, 2020 at 13:25

Sometimes .concat() is better than .push() since .concat() returns the new array whereas .push() returns the length of the array.

Therefore, if you are setting a variable equal to the result, use .concat() .

In this case, newArray will return 5 (the length of the array).

However, here newArray will return [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}, {'id': 5}].

If you're doing jQuery, and you've got a serializeArray thing going on concerning your form data, such as :

...and you need to add a key/value to this array with the same structure, for instance when posting to a PHP ajax request then this :

anoraq's user avatar

New solution with ES6

Default object

Another object

Object assign ES6

Ugur's user avatar

  • Please make your answer more elaborate. Explain how it works. –  mip Commented Dec 7, 2019 at 15:00
  • 1 I think it should be ary1 = [{'id': 1}, {'id': 2}];ary2 = [{'id': 3}];join = [...ary1,...ary2]; –  Soth Commented Feb 26, 2021 at 4:02

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged javascript arrays key-value or ask your own question .

  • Featured on Meta
  • We spent a sprint addressing your requests — here’s how it went
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • The [lib] tag is being burninated
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Did Joe Biden refer to himself as a black woman?
  • Which "other travel websites" does Booking.com fetch reviews from?
  • Identify the story about an author whose work-in-progress is completed by a computer
  • How can I search File Explorer for files only (i.e. exclude folders) in Windows 10?
  • How can I power both sides of breaker box with two 120 volt battery backups?
  • Signature of Rav Ovadia Hedaya
  • Can I put multiple journeys and dates on one train ticket in UK?
  • How are Boggarts created?
  • Why do jet aircraft need chocks when they have parking brakes?
  • What caused the builder to change plans midstream on this 1905 library in New England?
  • An algorithm for generating a permutation of N numbers ranging from 1 to N with the maximum of smallest neighbouring differences
  • Translation of the two lines of Latin in Shakespear's Venus and Adonis
  • How do we define addition?
  • The reading of the Ethiopian eunuch conversion story without Acts 8:37
  • Coincidence between coefficients of tanh(tan(x/2)) and Chow ring computations?
  • Equivalence of first/second choice with naive probability - I don't buy it
  • What is this rectangular SMD part with a stripe along one of the long edges?
  • How can I export my Location History now that this data is only stored locally on the phone?
  • Was I wrongfully denied boarding for a flight where the airliner lands to a gate that doesn't directly connect to the international part the airport?
  • What's the optimal taper ratio for a commerical short/medium haul aircraft?
  • Is this a Hadamard matrix?
  • How to arrange three identical habitable planets in one solar system in similar or, if possible, same orbit?
  • climate control and carbon sequestration via bulk air liquification
  • When, if ever, is bribery legal?

javascript create array key value pair

  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter

How to store a key=> value array in JavaScript ?

We have given two arrays containing keys and values and the task is to store it as a single entity in the form key => value in JavaScript. In JavaScript, the array is a single variable that is used to store different elements. It is usually used once we need to store a list of parts and access them by one variable. We can store key => value array in JavaScript Object using methods discussed below: 

Method 1: In this method we will use Object to store key => value in JavaScript. Objects, in JavaScript, is the most important data-type and forms the building blocks for modern JavaScript. These objects are quite different from JavaScript’s primitive data-types(Number, String, Boolean, null, undefined and symbol). Objects are more complex and each object may contain any combination of these primitive data-types as well as reference data-types. 

Approach: We will traverse through the whole array and one by one add the keys from the keys (array) and the corresponding values from values (array) in the Object. 

Example:  

Method 2: In this method we will use Map to store key => value in JavaScript. The map is a collection of elements where each element is stored as a key, value pair. Map objects can hold both objects and primitive values as either key or value. When we iterate over the map object it returns the key, value pair in the same order as inserted. 

Approach: We will traverse through the whole array and one by one add the keys from the keys (array) and the corresponding values from values (array) in the map. 

Method 3: In this method we will use reduce to store key => value in JavaScript. The reduce is method which is use iterate over the list of elements. This method is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator.

Example: 

Method 4: In this method we will use the forEach () method to store key => value in JavaScript. This method iterates over elements of an array and executes a callback function for each element. We can use this method to iterate over the keys array and simultaneously access corresponding values from the values array to create key-value pairs and store them in an object.

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples .

Please Login to comment...

Similar reads.

  • Web Technologies
  • JavaScript-Questions

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Add a Key/Value pair to all Objects in Array in JavaScript

avatar

Last updated: Mar 1, 2024 Reading time · 5 min

banner

# Table of Contents

  • Add a Key/Value pair to all Objects in Array using Array.map()
  • Using Object.assign() instead of the spread syntax (...)
  • Conditionally adding a key-value pair to all objects in an array
  • Add a Key/Value pair to all Objects in an Array using for...of
  • Add a Key/Value pair to all Objects in an Array using a for loop

# Add a Key/Value pair to all Objects in Array in JavaScript

To add a key/value pair to all objects in an array:

  • Use the Array.forEach() method to iterate over the array.
  • Use dot notation to add a key/value pair to each object.
  • The key/value pair will get added to all objects in the array.

add key value pair to all objects in array

The function we passed to the Array.forEach() method gets called with each element (object) in the array.

On each iteration, we add a key/value pair to the current object .

If the name of the key you need to add to the object contains hyphens, spaces or starts with a number, use bracket notation to add the key to each object.

The Array.forEach() method iterates over the array and adds the key-value pair to each object in place.

If you'd rather not mutate the original array, use the Array.map() method.

# Add a Key/Value pair to all Objects in Array using Array.map()

This is a three-step process:

  • Use the Array.map() method to iterate over the array.
  • Use the spread syntax to add a key/value pair to each object.
  • The key/value pair will get added to all objects in the new array.

add key value pair to all objects in array using array map

The function we passed to the Array.map() method gets called with each element (object) in the array.

We used the spread syntax (...) to unpack the key/value pairs of each object and then we added an additional key/value pair.

We basically transfer over the id property and add a color property to each object.

The Array.map() method is different than Array.forEach() because map() returns a new array, whereas forEach() returns undefined .

When using the forEach() method, we mutate the array in place.

# Using Object.assign() instead of the spread syntax (...)

You can also use the Object.assign() method instead of using the spread syntax.

using object assign instead of the spread syntax

We used the Object.assign() method to copy the key-value pairs of one or more objects into a target object.

The arguments we passed to the Object.assign() method are:

  • the target object - the object to which the provided properties will be applied.
  • the source object(s) - one or more objects that contain the properties we want to apply to the target object.

You can imagine that the key-value pairs of the object we passed as the second argument to Object.assign() , get copied into the object we supplied for the first argument.

# Conditionally adding a key-value pair to all objects in an array

If you need to conditionally add a key-value pair to all objects in an array, use the ternary operator.

conditionally adding key value pair to all objects in array

The ternary operator is very similar to an if/else statement.

In the example, we check if the current object's id property is greater than 1 .

If the condition is met, the string Bobby is returned for the name property, otherwise, the string Alice is returned.

Here is the equivalent if/else statement.

If the object's id property is greater than 1 , the if block runs, otherwise, the else block runs.

# Add a Key/Value pair to all Objects in an Array using for...of

You can also use a simple for...of loop to add a key-value pair to all objects in an array.

The for...of statement is used to loop over iterable objects like arrays, strings, Map , Set and NodeList objects and generators .

On each iteration, we add a new key-value pair to the current object, in place.

# Add a Key/Value pair to all Objects in an Array using a for loop

You can also use a basic for loop to add a key-value pair to all objects in an array.

The basic for loop is quite verbose in comparison to forEach() or for...of .

We also have to use the index to access the object of the current iteration before adding a key-value pair.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • Check if all Values in Array are Equal in JavaScript
  • Remove Property from all Objects in Array in JavaScript
  • How to skip over an Element or an Index in .map() in JS

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

Object.entries()

The Object.entries() static method returns an array of a given object's own enumerable string-keyed property key-value pairs.

Return value

An array of the given object's own enumerable string-keyed property key-value pairs. Each key-value pair is an array with two elements: the first element is the property key (which is always a string), and the second element is the property value.

Description

Object.entries() returns an array whose elements are arrays corresponding to the enumerable string-keyed property key-value pairs found directly upon object . This is the same as iterating with a for...in loop, except that a for...in loop enumerates properties in the prototype chain as well. The order of the array returned by Object.entries() is the same as that provided by a for...in loop.

If you only need the property keys, use Object.keys() instead. If you only need the property values, use Object.values() instead.

Using Object.entries()

Using object.entries() on primitives.

Non-object arguments are coerced to objects . undefined and null cannot be coerced to objects and throw a TypeError upfront. Only strings may have own enumerable properties, while all other primitives return an empty array.

Converting an Object to a Map

The Map() constructor accepts an iterable of entries . With Object.entries , you can easily convert from Object to Map :

Iterating through an Object

Using array destructuring , you can iterate through objects easily.

Specifications

Specification

Object.keys, values, entries

Let’s step away from the individual data structures and talk about the iterations over them.

In the previous chapter we saw methods map.keys() , map.values() , map.entries() .

These methods are generic, there is a common agreement to use them for data structures. If we ever create a data structure of our own, we should implement them too.

They are supported for:

Plain objects also support similar methods, but the syntax is a bit different.

For plain objects, the following methods are available:

  • Object.keys(obj) – returns an array of keys.
  • Object.values(obj) – returns an array of values.
  • Object.entries(obj) – returns an array of [key, value] pairs.

Please note the distinctions (compared to map for example):

Map Object
Call syntax , but not
Returns iterable “real” Array

The first difference is that we have to call Object.keys(obj) , and not obj.keys() .

Why so? The main reason is flexibility. Remember, objects are a base of all complex structures in JavaScript. So we may have an object of our own like data that implements its own data.values() method. And we still can call Object.values(data) on it.

The second difference is that Object.* methods return “real” array objects, not just an iterable. That’s mainly for historical reasons.

For instance:

  • Object.keys(user) = ["name", "age"]
  • Object.values(user) = ["John", 30]
  • Object.entries(user) = [ ["name","John"], ["age",30] ]

Here’s an example of using Object.values to loop over property values:

Just like a for..in loop, these methods ignore properties that use Symbol(...) as keys.

Usually that’s convenient. But if we want symbolic keys too, then there’s a separate method Object.getOwnPropertySymbols that returns an array of only symbolic keys. Also, there exist a method Reflect.ownKeys(obj) that returns all keys.

Transforming objects

Objects lack many methods that exist for arrays, e.g. map , filter and others.

If we’d like to apply them, then we can use Object.entries followed by Object.fromEntries :

  • Use Object.entries(obj) to get an array of key/value pairs from obj .
  • Use array methods on that array, e.g. map , to transform these key/value pairs.
  • Use Object.fromEntries(array) on the resulting array to turn it back into an object.

For example, we have an object with prices, and would like to double them:

It may look difficult at first sight, but becomes easy to understand after you use it once or twice. We can make powerful chains of transforms this way.

Sum the properties

There is a salaries object with arbitrary number of salaries.

Write the function sumSalaries(salaries) that returns the sum of all salaries using Object.values and the for..of loop.

If salaries is empty, then the result must be 0 .

Open a sandbox with tests.

Or, optionally, we could also get the sum using Object.values and reduce :

Open the solution with tests in a sandbox.

Count properties

Write a function count(obj) that returns the number of properties in the object:

Try to make the code as short as possible.

P.S. Ignore symbolic properties, count only “regular” ones.

  • If you have suggestions what to improve - please submit a GitHub issue or a pull request instead of commenting.
  • If you can't understand something in the article – please elaborate.
  • To insert few words of code, use the <code> tag, for several lines – wrap them in <pre> tag, for more than 10 lines – use a sandbox ( plnkr , jsbin , codepen …)

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy

JavaScript Object Keys Tutorial – How to Use a JS Key-Value Pair

Amy Haddad

You can group related data together into a single data structure by using a JavaScript object, like this:

An object contains properties, or key-value pairs. The desk object above has four properties. Each property has a name, which is also called a key, and a corresponding value.

For instance, the key height has the value "4 feet" . Together, the key and value make up a single property.

The desk object contains data about a desk. In fact, this is a reason why you’d use a JavaScript object: to store data. It’s also simple to retrieve the data that you store in an object. These aspects make objects very useful.

This article will get you up and running with JavaScript objects:

  • how to create an object
  • how to store data in an object
  • and retrieve data from it.

Let’s start by creating an object.

How to Create an Object in JavaScript

I'll create an object called pizza below, and add key-value pairs to it.

The keys are to the left of the colon : and the values are to the right of it. Each key-value pair is a property . There are three properties in this example:

  • The key topping has a value “cheese” .
  • The key sauce has a value “marinara” .
  • The key size has a value “small” .

Each property is separated by a comma. All of the properties are wrapped in curly braces.

This is the basic object syntax. But there are a few rules to keep in mind when creating JavaScript objects.

Object Keys in JavaScript

Each key in your JavaScript object must be a string, symbol, or number.

Take a close look at the example below. The key names 1 and 2 are actually coerced into strings.

It’s a difference made clear when you print the object.

There’s another rule to keep in mind about key names: if your key name contains spaces, you need to wrap it in quotes.

Take a look at the programmer object below. Notice the last key name, "current project name" . This key name contains spaces so, I wrapped it in quotes.

Object Values in JavaScript

A value, on the other hand, can be any data type, including an array, number, or boolean. The values in the above example contain these types: string, integer, boolean, and an array.

You can even use a function as a value, in which case it’s known as a method. sounds() , in the object below, is an example.

Now say you want to add or delete a key-value pair. Or you simply want to retrieve an object’s value.

You can do these things by using dot or bracket notation, which we’ll tackle next.

How Dot Notation and Bracket Notation Work in JavaScript

Dot notation and bracket notation are two ways to access and use an object’s properties. You’ll probably find yourself reaching for dot notation more often, so we'll start with that.

How to Add a Key-Value Pair with Dot Notation in JavaScript

I'll create an empty book object below.

To add a key-value pair using dot notation, use the syntax:

objectName.keyName = value

This is the code to add the key (author) and value ("Jane Smith") to the book object:

Here's a breakdown of the above code:

  • book is the object's name
  • author is the key name
  • "Jane Smith" is the value

When I print the book object, I’ll see the newly added key-value pair.

I’ll add another key-value pair to the book object.

The book object now has two properties.

How to Access Data in a JavaScript Object Using Dot Notation

You can also use dot notation on a key to access the related value.

Consider this basketballPlayer object.

Say you want to retrieve the value “shooting guard.” This is the syntax to use:

objectName.keyName

Let's put this syntax to use to get and print the "shooting guard" value.

  • basketballPlayer is the object's name
  • position is the key name

This is another example.

How to Delete a Key-Value Pair in JavaScript

To delete a key-value pair use the delete operator. This the syntax:

  • delete objectName.keyName

So to delete the height key and its value from the basketballPlayer object, you’d write this code:

As a result, the basketballPlayer object now has three key-value pairs.

You’ll probably find yourself reaching for dot notation frequently, though there are certain requirements to be aware of.

When using dot notation, key names can’t contain spaces, hyphens, or start with a number.

For example, say I try to add a key that contains spaces using dot notation. I’ll get an error.

So dot notation won’t work in every situation. That’s why there’s another option: bracket notation.

How to Add a Key-Value Pair Using Bracket Notation in JavaScript

Just like dot notation, you can use bracket notation to add a key-value pair to an object.

Bracket notation offers more flexibility than dot notation. That’s because key names can include spaces and hyphens, and they can start with numbers.

I'll create an employee object below.

Now I want to add a key-value pair using bracket notation. This is the syntax:

objectName[“keyName”] = value

So this is how I’d add the key (occupation) and value (sales) to the employee object:

  • employee is the object's name
  • "occupation" is the key name
  • "sales" is the value

Below are several more examples that use bracket notation's flexibility to add a variety of key-value pairs.

When I print the employee object, it looks like this:

With this information in mind, we can add the “shooting percentage” key to the basketballPlayer object from above.

You may remember that dot notation left us with an error when we tried to add a key that included spaces.

But bracket notation leaves us error-free, as you can see here:

This is the result when I print the object:

How to Access Data in a JavaScript Object Using Bracket Notation

You can also use bracket notation on a key to access the related value.

Recall the animal object from the start of the article.

Let's get the value associated with the key, name . To do this, wrap the key name quotes and put it in brackets. This is the syntax:

objectName[“keyName”]

Here's the code you'd write with bracket notation: animal["name"]; .

This is a breakdown of the above code:

  • animal is the object's name
  • ["name"] is the key name enclosed in square brackets

Here’s another example.

Note that sounds() is a method, which is why I added the parentheses at the end to invoke it.

This is how you’d invoke a method using dot notation.

JavaScript Object Methods

You know how to access specific properties. But what if you want all of the keys or all of the values from an object?

There are two methods that will give you the information you need.

Use the Object.keys() method to retrieve all of the key names from an object.

This is the syntax:

Object.keys(objectName)

We can use this method on the above runner object.

If you print the result, you’ll get an array of the object’s keys.

Likewise, you can use the Object.values() method to get all of the values from an object. This is the syntax:

Object.values(objectName)

Now we'll get all of the values from the runner object.

We’ve covered a lot of ground. Here’s a summary of the key ideas:

  • Use objects to store data as properties (key-value pairs).
  • Key names must be strings, symbols, or numbers.
  • Values can be any type.

Access object properties:

  • Dot notation: objectName.keyName
  • Bracket notation: objectName[“keyName”]

Delete a property:

There’s a lot you can do with objects. And now you’ve got some of the basics so you can take advantage of this powerful JavaScript data type.

I write about learning to program, and the best ways to go about it on amymhaddad.com . I also tweet about programming, learning, and productivity: @amymhaddad .

Programmer and writer | howtolearneffectively.com | dailyskillplanner.com

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Currently Reading :

Currently reading:

Table of Contents

JavaScript: Obtain key-value pairs in an array

Pooja Hariharan

Software Developer

Published on  Mon Mar 14 2022

In this article let us understand what a “key” and a “value” is in an array is & also look at the different methods by which we can obtain these key-value pairs

What are a key and value in an array?

Keys are indexes and values are elements of an associative array. Associative arrays are basically objects in JavaScript where indexes are replaced by user-defined keys. They do not have a length property like a normal array and cannot be traversed using a normal for loop.

Here’s an example of an associative array

Unlike simple arrays, we use curly braces instead of square brackets. The content or values of associative arrays is accessed by keys.

In the above array, one, two & three are keys, and 1, 2 & 3 are values. These can be obtained individually using the keys() & values() methods as shown below

Different methods to obtain key-value pairs

Now that we know how to get keys & values in an array, let us look at the different methods to obtain key-value pairs.

Let us first store the previously extracted keys & values in separate arrays

Method 1: Using an object to store key => value pairs

In this method we store the elements from the “keys” array & the corresponding values from the “values” array using an associative array "obj"

Method 2: Using the map() method

A map is a collection of elements where each element is stored as a key, value pair. The objects of map type can hold both objects and primitive values as either key or value. On traversing through the map object, it returns the key, value pair in the same order as inserted.

Browser Support

The following are the lowest browser versions that fully support the following methods.

keys() method

Chrome: 38; Firefox: 28; Safari: 8; Opera: 25; Edge: 12

values() method

Chrome: 54; Firefox: 47; Safari: 41; Opera: 10.1; Edge: 14

map() method

Chrome: All versions; Firefox: 1.5; Safari: All versions; Opera: All versions; Edge: 9.0

About the author

Pooja Hariharan is an experienced data scientist with a strong focus on predictive analytics and machine learning. She excels in turning data insights into strategic solutions for business improvements.

Related Blogs

Get current time using JavaScript

JavaScript require vs import

Check if a variable is of function type or not

Associative array in JavaScript

What is Javascript Object.assign?

Vinayaka Tadepalli

JavaScript Capitalize First Letter - How to Uppercase the First Letter in a Word with JS

Browse Flexiple's talent pool

Explore our network of top tech talent. Find the perfect match for your dream team.

  • Programmers
  • React Native
  • Ruby on Rails

JavaScript Key Value Array

A JavaScript key-value array is a data structure that allows you to store an ordered collection of key-value pairs.

Introduction

In an object-oriented programming paradigm, key-value arrays are a convenient way to manage objects. This makes it easy to add, modify, and delete key-value pairs.

With its intuitive syntax, JavaScript key-value array allows developers to access values by using keys, making it a reliable and flexible tool.

This type of array can be useful in various programming scenarios. Such as storing and retrieving data from a database. Or managing configuration settings in an application.

In JavaScript, you can create an array of key-value pairs using an object literal syntax or the Map constructor.

Here are examples of both:

1. Using object literal syntax

In this example, keyValueArray is an array containing three objects, each with a key and value property.

How to access JavaScript key-value pair in an array of object literal syntax?

There are two ways to access key-value pair in an array of object literal syntax-

Using dot notation

Using bracket notation

2. Using the Map constructor

In this example, keyValueMap is a Map object containing three key-value pairs.

How to access JavaScript key-value pair in a Map constructor?

You can access the values by calling get() method of the Map object and passing the key as an argument, like this:

The get() method returns the value associated with that key, or undefined if the key is not found in the Map object.

Note that you can also use the has() method to check whether a particular key exists in the Map object before calling the get() method to avoid errors.

When used properly, a key-value array can help improve the efficiency and performance of your JavaScript code.

In addition, You might also like – Javascript homework help

Share Article:

Javascript round to 2 decimal places, center text in bootstrap card overlay, leave a reply cancel reply.

Save my name, email, and website in this browser for the next time I comment.

How to Push Key-Value Pair Into an Array Using JavaScript

  • JavaScript Howtos
  • How to Push Key-Value Pair Into an Array …

Push Key-Value Pair Into an Array Using JavaScript

Use map() to push key-value pair into an array in javascript, use reduce() to push key-value pair into an array in javascript, use jquery to push key-value pair into an array in javascript.

How to Push Key-Value Pair Into an Array Using JavaScript

This article delves into various methods to push key-value pairs into an array using JavaScript, focusing on different approaches, from manual object creation to leveraging built-in functions.

Demonstrating code snippets and their respective outputs, we’ll explore techniques like for loops, map() , reduce() , and even the use of jQuery’s $.each() function.

By understanding these techniques, you’ll have a comprehensive toolkit to efficiently organize and manipulate data within arrays.

Let’s begin by exploring a method to achieve this without using built-in functions and methods in JavaScript.

JavaScript Code:

In our code above, we started with two arrays: arr1 , containing keys ( left and top ), and arr2 , an empty array we wanted to populate with key-value pairs. We then created an empty object called obj to store the key-value pairs before pushing them into arr2 .

Using a for loop, we iterated through the elements in arr1 , which occurred twice, once for left and once for top . Within the loop, we utilized bracket notation ( obj[key] ) to assign a value of 0 to each key in the obj object, effectively creating key-value pairs.

Once the loop was completed, we had an object obj with the desired key-value pairs. We then pushed this obj object into arr2 using the push() method.

Finally, we logged arr2 to the console, displaying the array containing our key-value pairs.

Now, let’s move to built-in functions and methods to push key-value pairs into arr2 .

ECMAScript 6 (ES6) introduced arrow functions, a concise way to write functions, particularly when the function has only one statement. This feature enhances code efficiency and readability, streamlining function syntax using the => operator.

Arrow functions prove especially useful when used with methods like map() in JavaScript.

The map() method makes a new array by calling a function once for every array’s element. It does not modify the original array, and it runs for empty elements.

In the JavaScript code snippet below, we can see the map() method in action. This method is invoked on an array named arr1 , which contains the initial values left and top .

An arrow function is used to transform each element of arr1 into an object where the original element serves as a property with a value of 0 . This transformation results in a new array named arr2 , which holds objects with the properties left and top , each initialized to 0 .

In the output, we can see that the map() method effectively creates distinct objects with the same data but different properties. In this case, each object has a single property based on the values obtained from the original array, showcasing the versatility and usefulness of the map() method when combined with arrow functions in modern JavaScript development.

The reduce() method in JavaScript is a powerful tool for processing arrays, allowing the execution of a reducer function that ultimately yields a single accumulated value as a result.

Similar to the map() method, reduce() doesn’t modify the original array, even when encountering empty elements within the array. Let’s see a practical example to illustrate this.

Once again, we began with arr1 , which contained keys ( left and top ). Our goal was to create an object arr2 with key-value pairs.

To achieve this, we employed the reduce() method on arr1 , iterating over its elements and accumulating a single result, in this case, an object.

Within the reduce() method, a callback function was provided. This function had two parameters: obj (the accumulator) and arrValue (the current element in the array).

In this callback function, we set obj[arrValue] to 0 , effectively creating a key-value pair in the obj object. The key was the current element from arr1 , and the value was 0 .

As we progressed, the reduce() method accumulated these key-value pairs in the obj object.

Finally, we logged arr2 to the console, presenting the object with the desired key-value pairs.

Let’s say you’re aiming to structure a key-value pair within an array based on two properties ( left and top ) from an object. We’ll demonstrate how to achieve this using jQuery.

Example Code:

In this example, we used jQuery’s $.each() function to achieve the same result. We started with arr1 , which contained keys ( left and top ).

Recall that our goal was to create an array arr2 with objects where each key from arr1 mapped to a value of 0 . To accomplish this, we initialized an empty object obj to store our key-value pairs.

Next, we utilized $.each() to iterate over the elements in arr1 . Inside the callback function, index represented the index of the element, and value was the current element.

For each element in arr1 , we created a key-value pair in the obj object, where the key was the current element ( value ) and the value was 0 .

Once the loop was completed, we proceeded to push the obj object into arr2 using the push() method. Finally, we logged arr2 to the console, presenting an array containing our key-value pairs.

Now, if you have two arrays and you want to pair all elements from both arrays into a third array, you can achieve this by using a loop or JavaScript’s built-in methods.

Here’s how you can do it:

Here, we started with two arrays: keys and values . To capture the resulting objects, we also initialized an empty array arr , which was intended to hold one or more objects, each representing a set of key-value pairs.

Additionally, we set up an empty object ‘obj’ to store the key-value pairs for each iteration of the loop.

Using a for loop, we iterated through the elements of both keys and values. This loop proceeded as long as i was less than the length of both arrays.

Within the loop, we accessed elements from both keys and values using the current value of i . This allowed us to create a key-value pair in the obj object, with the key taken from the keys array and the value extracted from the values array.

The loop continued until it had processed all elements present in both arrays, generating key-value pairs for each pair of elements in the two arrays.

Once the loop concluded, we had an obj object containing all the key-value pairs.

We utilized the push() method to add the obj object to the arr array. This action effectively inserted the object into the array as a single element.

Finally, we logged the arr array to the console, presenting an array that held a single object with all the desired key-value pairs.

JavaScript offers multiple ways to incorporate key-value pairs into arrays, each catering to distinct programming needs and preferences. From fundamental iterations using for loops and manual object creation to leveraging modern constructs like map() and reduce() , developers can select the most appropriate method based on context and efficiency requirements.

Additionally, we explored how jQuery simplifies this process using its $.each() function. Armed with this knowledge, you can now effectively manage and organize data within arrays, enhancing your JavaScript programming capabilities.

Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

Related Article - JavaScript Array

  • How to Check if Array Contains Value in JavaScript
  • How to Create Array of Specific Length in JavaScript
  • How to Convert Array to String in JavaScript
  • How to Remove First Element From an Array in JavaScript
  • How to Search Objects From an Array in JavaScript
  • How to Convert Arguments to an Array in JavaScript

IMAGES

  1. Array Keys And Values Pair In Javascript || Javascript Tutorial || Javascript Course || Javascript

    javascript create array key value pair

  2. Create JavaScript Key Value Array Pairs Using Easy Examples

    javascript create array key value pair

  3. How To Merge Two Array of String Into A Key/Value Pair (Object) In

    javascript create array key value pair

  4. Push Key-Value Pair Into an Array Using JavaScript

    javascript create array key value pair

  5. Create an array of key-value pair arrays from a given object

    javascript create array key value pair

  6. Adding A Key/value Pair To An Array In JavaScript

    javascript create array key value pair

VIDEO

  1. 6/14

  2. Use State hook With Array|key Value And Map in React.js @Nj.tech14

  3. How can I add a key/value pair to a JavaScript object?

  4. #11 JavaScript Map Methods

  5. 29

  6. How Can I Add A Key And Value Pair To A JavaScript Object

COMMENTS

  1. Best way to store a key=>value array in JavaScript?

    What's the best way to store a key=>value array in javascript, and how can that be looped through? The key of each element should be a tag, such as {id} or just id and the value should be the numerical value of the id.

  2. How to add a new object (key-value pair) to an array in ...

    I have an array as : items=[{'id':1},{'id':2},{'id':3},{'id':4}]; How should I add a new pair {'id':5} to the array?

  3. How to store a key=> value array in JavaScript - GeeksforGeeks

    This method iterates over elements of an array and executes a callback function for each element. We can use this method to iterate over the keys array and simultaneously access corresponding values from the values array to create key-value pairs and store them in an object. Syntax: const obj = {}; keys.forEach((key, index) =>

  4. Add a Key/Value pair to all Objects in Array in JavaScript

    To add a key/value pair to all objects in an array: Use the Array.forEach() method to iterate over the array. Use dot notation to add a key/value pair to each object.

  5. Object.entries() - JavaScript | MDN - MDN Web Docs

    The Object.entries() static method returns an array of a given object's own enumerable string-keyed property key-value pairs.

  6. Object.keys, values, entries - The Modern JavaScript Tutorial

    Use Object.entries(obj) to get an array of key/value pairs from obj. Use array methods on that array, e.g. map , to transform these key/value pairs. Use Object.fromEntries(array) on the resulting array to turn it back into an object.

  7. JavaScript Object Keys Tutorial – How to Use a JS Key-Value Pair

    How to Add a Key-Value Pair with Dot Notation in JavaScript. I'll create an empty book object below. const book = {}; To add a key-value pair using dot notation, use the syntax: objectName.keyName = value. This is the code to add the key (author) and value ("Jane Smith") to the book object: book.author = "Jane Smith"; Here's a breakdown of the ...

  8. JavaScript: Obtain key-value pairs - Flexiple

    Learn how to use JavaScript to obtain key-value pairs in an array efficiently. Get practical tips and examples for working with data structures.

  9. JavaScript Key Value Array - Letstacle

    In JavaScript, you can create an array of key-value pairs using an object literal syntax or the Map constructor. Here are examples of both: 1. Using object literal syntax. In this example, keyValueArray is an array containing three objects, each with a key and value property. const keyValueArray = [.

  10. Key-Value Pair Into an Array Using JavaScript">How to Push Key-Value Pair Into an Array Using JavaScript

    This article delves into various methods to push key-value pairs into an array using JavaScript, focusing on different approaches, from manual object creation to leveraging built-in functions. Demonstrating code snippets and their respective outputs, we’ll explore techniques like for loops, map() , reduce() , and even the use of jQuery’s ...