You just assign to those properties:
obj["first-name"] = array[0];
obj["last-name"] = array[1];
Example:
var array = ["lionel", "messi"];
var obj = {
"first-name": "cristiano",
"last-name": "ronaldo"
};
obj["first-name"] = array[0];
obj["last-name"] = array[1];
console.log(obj);
In ES2015+, you can use a destructuring assignment:
[obj["first-name"], obj["last-name"]] = array;
Example:
var array = ["lionel", "messi"];
var obj = {
"first-name": "cristiano",
"last-name": "ronaldo"
};
[obj["first-name"], obj["last-name"]] = array;
console.log(obj);
In a comment you've said:
but what if I had to do it dynamically? How do I loop over both in the array/object?
If you mean that you want to assign the entries from array to the object properties in obj by their position, beware that object property order is new as of ES2015 and it's easily misunderstood.
But with a fully ES2015+ compliant JavaScript engine, if your object really is defined as:
var obj = {
"first-name": "cristiano",
"last-name": "ronaldo"
};
...then Object.getOwnPropertyNames will reliably return ["first-name", "last-name"] (Object.keys is not guaranteed to), because:
- The properties were created in that order by the object initializer
- They're "own" properties
- They have string names (not Symbol names),
- They don't look like array indexes, and
- It's an ordinary object
Yes, that's quite a lot of caveats. So you could use that, like this:
Object.getOwnPropertyNames(obj).forEach((key, index) => {
obj[key] = array[index];
});
Example:
var array = ["lionel", "messi"];
var obj = {
"first-name": "cristiano",
"last-name": "ronaldo"
};
Object.getOwnPropertyNames(obj).forEach((key, index) => {
obj[key] = array[index];
});
console.log(obj);
Again: That only works on a fully ES2015+ compliant JavaScript engine, with an object defined as shown above. The order in which properties are reported by getOwnPropertyNames is potentially complex; details in the spec.