How can I add a key/value pair to a JavaScript object?
There are two ways to add new properties to an object:
var obj = {
key1: value1,
key2: value2
};
Using dot notation:
obj.key3 = "value3";
Using square bracket notation:
obj["key3"] = "value3";
The first form is used when you know the name of the property. The second form is used when the name of the property is dynamically determined. Like in this example:
var getProperty = function (propertyName) {
return obj[propertyName];
};
getProperty("key1");
getProperty("key2");
getProperty("key3");
A real JavaScript array can be constructed using either:
The Array literal notation:
var arr = [];
The Array constructor notation:
var arr = new Array();
How to add key values pair in object in JAVASCRIPT?
You cannot push on to an object. You have to specify the key and value like so:
Literally
divByThree.key = value
Note, in the above example, key is the literal key name, and so you would access it like:
divByThree.key
divByThree['key'] // note the quotes around key
Dynamically
If you want to create a dynamic key based on a js variable for example, you can do:
const keyName = 'myKey';
divByThree[keyName] = value;
To access the value, you can do:
divByThree[keyName]; // no quotes. Value of keyName variable
divByThree['myKey'];
divByThree.myKey;
how do i add a key-value pair to an object in state of functional components
the problem comes from your accessor for choice
in the onClick function. The good syntax should be (because choice is accessible directly as a variable in your component)
onClick={()=>{
setChoice( { ...choice, key:val } );
}
choice
is state variable, so directly accessible by its name. No need to link to your component props with props.choicesetChoice should take as an argument the original variable, plus the new key/value pair. Thus the destructuring of ...choice and the added member variable key:value.
Edit:
if you want your updates to be more sound with the React way, you should use the callback syntax. Finally you would have
setChoice(choice => { return {...choice, key:val}})
This preventing some noodling, coming from the asynchronous nature of state updates in React.
Add key-value pair in Javascript object
Iterate the Object#keys of the object with Array#map, and return an object in the format that you want.
Note: to ensure the order of the objects, you can sort the keys using String#localeCompare with the numeric: true
option.
var data = {
'Country1' : '20',
'country2': '30',
'country3': '40',
'country4' : '45'
};
var result = Object.keys(data)
.sort(function(a, b) { // if you need to ensure the order of the keys
return a.localeCompare(b, undefined, { numeric: true})
})
.map(function(key) {
return {
name: key,
value: data[key]
};
});
console.log(result);
How to add a new Key value pair in JavaScript Object
I think map
is the best way.
Try this:
var arr = [
{
name: "ABC",
grade: 2
},
{
name: "DEF",
grade: 3
},
]
var newArr = arr.map(obj =>({ ...obj, id: obj.grade*10+3}))
console.log(newArr)
How to structure a function to add a key-value pair to a javascript object
Try:
const welcomeMessages = {
english: "Welcome",
french: "Bienvenue",
italian: "Benvenuto",
spanish: "bienvenido",
russian: "Добро пожаловать",
chinese: "歡迎",
finnish: "Tervetuloa"
};
function addWelcomeMessage(language, message) {
welcomeMessages[language] = message;
}
You could also add a small check to see if the message already exists, so that you don't have duplicate entries.
const welcomeMessages = {
english: "Welcome",
french: "Bienvenue",
italian: "Benvenuto",
spanish: "bienvenido",
russian: "Добро пожаловать",
chinese: "歡迎",
finnish: "Tervetuloa"
};
function addWelcomeMessage(language, message) {
if(!welcomeMessages[language]) welcomeMessages[language] = message;
}
Another way is to use Object.assign()
function
const welcomeMessages = {
english: "Welcome",
french: "Bienvenue",
italian: "Benvenuto",
spanish: "bienvenido",
russian: "Добро пожаловать",
chinese: "歡迎",
finnish: "Tervetuloa"
};
function addWelcomeMessage(language, message) {
Object.assign(welcomeMessages, {language, message});
}
Though you don't necessarily have to wrap them inside a function, you can just do this instead:
Object.assign(welcomeMessages, {"danés", "Velkommen"});
Object.assign(welcomeMessages, {"zulú", "Ukwamukela"});
How to add key/value pair in Javascript object at the start
While objects have actually (ES5) no order, you could generate a new object with Object.assign
and use the new property as object to start with and assign the given object to it. The new object has properties in creation order.
var object = { last_name: "john", age: 23, city: "London" };
object = Object.assign({ first_name: "Samuel" }, object);
console.log(object);
Related Topics
Is There a JavaScript/Jquery Dom Change Listener
Ways to Deal With #Document Under Iframe
Http Get Request in JavaScript
When Should I Use Double or Single Quotes in JavaScript
Download File Using JavaScript/Jquery
How to Get Jquery to Perform a Synchronous, Rather Than Asynchronous, Ajax Request
How to Access React Instance (This) Inside Event Handler
How to Find the Sum of an Array of Numbers
Updating Address Bar With New Url Without Hash or Reloading the Page
How to Add a Class to a Given Element
Fastest Way to Flatten/Un-Flatten Nested JavaScript Objects
How to Print a Circular Structure in a Json-Like Format
Pass in an Array of Deferreds to $.When()
Can Someone Explain the "Debounce" Function in JavaScript
Access Java/Servlet/Jsp/Jstl/El Variables in JavaScript
A Partial View Passing a Collection Using the Html.Begincollectionitem Helper
JavaScript Raises Syntaxerror With Data Rendered in Jinja Template