In ES6...
In ES6, you can use a destructuring assignment;
ary.push({[name]: val});
However, given this is ES6 syntax, the usual caveats apply; this will not work in some browsers (noticably, IE and Edge 13)... although Babel will transpile this for you.
Without ES6 (legacy browser support)...
You need to define an object and use square bracket notation to set the property;
var obj = {};
obj[name] = val;
ary.push(obj);
If you get the urge to read into it more, see this article on the differences between square bracket and dot notation.
In ES6...
In ES6, you can use a destructuring assignment;
ary.push({[name]: val});
However, given this is ES6 syntax, the usual caveats apply; this will not work in some browsers (noticably, IE and Edge 13)... although Babel will transpile this for you.
Without ES6 (legacy browser support)...
You need to define an object and use square bracket notation to set the property;
var obj = {};
obj[name] = val;
ary.push(obj);
If you get the urge to read into it more, see this article on the differences between square bracket and dot notation.
var ary = [];
function pushToAry(name, val) {
var obj = {};
obj[name] = val;
ary.push(obj);
}
pushToAry("myName", "myVal");
Having just fully read your question though, all you need is the following
$(your collection of form els).serializeArray();
Good old jQuery
How can I add a key/value pair to a JavaScript object? - Stack Overflow
javascript - React - how to add dynamic key/value pair to an object? - Stack Overflow
How to add key and a dynamic value pair for each object in the array ?
How do I create a typed dynamic key-value store?
You can accomplish what you want using computed expression (I'm not really sure if you are trying to do that already). So your appendInput function should look something like this:
appendInput() {
var objectSize = Object.keys(this.state.milestonesValues).length;
var newInput = Object.assign({},
this.state.milestonesValues, {['milestone'+ objectSize]: ''});
this.setState({
milestonesValues: newInput)
});
}
Use this:
appendInput() {
var milestonesValues = Object.assign({}, this.state.milestonesValues);
var objectSize = Object.keys(milestonesValues).length;
var newInput = `milestone${objectSize}`;
milestonesValues[newInput] = '';
this.setState({ milestonesValues });
}
Check this example:
let data = {
milestonesValues : {
milestone0: "dssdsad",
milestone1: "",
milestone2: "",
milestone3: "",
}
};
function addelement(){
var milestonesValues = Object.assign({}, data.milestonesValues);
var objectSize = Object.keys(milestonesValues).length;
var newInput = `milestone${objectSize}`;
milestonesValues[newInput] = '';
data.milestonesValues = milestonesValues;
}
addelement();
console.log(data.milestonesValues);