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 to add a key value pair to an array in Javascript / Jquery
You can use Array.map()
to iterate the dataSource
array. Use an internal Array.reduce()
to iterate the Months, and add missing months to the current object:
const dataSource = [{"location":"France","January":79,"February":81,"March":23},{"location":"Germany","January":98,"February":83},{"location":"Japan","January":96,"March":11}];const Months = ["January","February","March"];
const result = dataSource.map(o => Months.reduce((obj, m) => m in obj ? obj : { ...obj, [m]: 100 }, o));
console.log(result);
Map a new key-value pair into an array of objects
map
returns new data, so your function should look something like this
loggedInUser: { self: boolean }[];
addUserStatus() {
const temp = this.userData.map((data, i) => ({ ...data,
"logged-in": this.loggedInUser[i].self
}))
this.userData = temp
}
If you want to modify this.userData
directly, you can use other methods like forEach
addUserStatus() {
this.userData.forEach((data, i) => {
data["logged-in"] = this.loggedInUser[i].self;
};
}
Add new key with Value to an array of nested Objects
You can create a small helper function to add ids to the data once you've received it (from whatever source - here I'm just passing it in as a prop to the component), and before you update the state.
Note: in this minimal working example I've initialised state with an empty array rather than null.
const { Component } = React;
// `map` over the data and for each
// object return an object with an id property
function addId(data) {
return data.map((obj, i) => {
return { id: i + 1, ...obj };
});
}
class Example extends Component {
constructor(props) {
super();
this.state = { data: [] };
}
// Use the helper function to add ids
// to the data objects, then set the new state
componentDidMount() {
const data = addId(this.props.data);
console.log(JSON.stringify(data));
this.setState({ data });
}
render() {
const { data } = this.state;
if (!data.length) return <div>No data</div>;
return (
<div>
{data.map(obj => {
return <div>{obj.id} {obj.name}</div>
})}
</div>
);
}
};
const data = [
{ name: 'Rita' },
{ name: 'Sue' },
{ name: 'Bob' }
];
ReactDOM.render(
<Example data={data} />,
document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
how to take a key value pair from array of objects and create a new object from that key value pair
Try this:
let arr = [
{name: "abcd", value: "xyz"},
{name: "pqr", value: "uvw"}
]
const result = {}
arr.forEach((element) => {
result[element.name] = element.value
})
console.log(result)
Add a Key Value Pair to an array of objects in javascript?
You can simply add properties ("fields") on the fly.
Try
myarray[0].Address = "123 Some St.";
or
myarray[0]["Address"] = "123 Some St.";
var myarray = [];
myarray.push({ "Name": 'Adam', "Age": 33});
myarray.push({ "Name": 'Emily', "Age": 32});
myarray[0]["Address"] = "123 Some St.";
console.log( JSON.stringify( myarray, null, 2 ) );
Related Topics
How to Vertically and Horizontally Center a Component in React
React-Native: Application Has Not Been Registered Error
How to Check If a Textbox Is Empty Using JavaScript
How to Convert Gmt Time to Ist Time in JavaScript
How to Convert Raw Mp3 Binary into Blob Url and Play It in Audio Tag
How to Remove All Null and Empty String Values from an Object
How to Pass Model Data in JavaScript
How to Add Class on Specific Div When Scroll
Expected to Return a Value At the End of Arrow Function Array-Callback-Return on Filter Function
How to Delete a Query String Parameter in JavaScript
How Could I Get the Latest Date from an Array of Dates - Javascript/Typescript
How to Download Pdf Automatically Using Js
Show Virtual Keyboard on Mobile Phones in JavaScript
Check If Image Exists on Server Using JavaScript
How to Create Expand/Collapse Function for Each Row of Table - Angular6
How to Change Color of Ag-Grid Cells for Dynamically Changing Data