In Javascript and Typescript, we often run into situations where we have an object with a certain set of properties, and then another variable that matches one or many keys in that object. This can cause all sorts of issues if the keys can be edited. For example, imagine the following situation:
JavaScript
let myUser = {
name: "John Doe",
email: "xyz@fjolt.com",
age: 15
}
function getUserDetails() {
let ourKeys = [ "name", "red", "age" ];
let constructedObject = {};
ourKeys.forEach(function(item) {
constructedObject[item] = myUser[item];
});
return constructedObject
}
We could imagine that ourKeys
maybe coming from a database, or an API. For the purposes of explanation, I've put it in a simple array. When we run through each of these keys using our forEach loop, we output details from myUser into a new Object, called constructedObject
.
from DZone.com Feed https://ift.tt/hjnJV5E
No comments:
Post a Comment