Say that we have an object like this one:
let obj = {a: "John", b: "Sarah", c: "Lara", d: "Joseph", e: "Roger"}
And an array of some of its keys:
let arr_of_keys = ["a", "d", "e"]
Is it possible to destructure the object using the predefined keys in the array, something along the lines of:
let {...arr_of_keys} = obj;
To finally end up with:
a = "John", d = "Joseph", e = "Roger"
You want a simple .reduce
method like the one below:
var result = arr_of_keys.reduce(function(o,item){
if(obj.hasOwnProperty(item)){
o[item] = obj[item];
}
return o;
}, {});
Here's an example:
let obj = {a: "John", b: "Sarah", c: "Lara", d: "Joseph", e: "Roger"} let arr_of_keys = ["a", "d", "e", "f"]; var result = arr_of_keys.reduce(function(o,item){ if(obj.hasOwnProperty(item)){ o[item] = obj[item]; } return o; }, {}); console.log(result)
Here's a JSFiddle runnable (since the built-in one returns a 503.)
Here is a possible helper function for the provided issue. I added a set conversion to remove possible duplications in order save resources. Also added simple error handling in form of console error messages.
const obj = {a: "John", b: "Sarah", c: "Lara", d: "Joseph", e: "Roger"} const arr_of_keys = ["a", "d", "e"]; const customObjectDescructurer = (arrayOfDesiredPropKeys, object) => { const setOfDesiredPropKeys = new Set(arrayOfDesiredPropKeys); const filteredObject = [...setOfDesiredPropKeys].reduce( (filteredObject, desiredPropKey) => { if(object.hasOwnProperty(desiredPropKey)){ filteredObject[desiredPropKey] = object[desiredPropKey]; } else { console.error(` The given ${desiredPropKey}, does not exist in ${object} object. `); } return filteredObject; }, {}); return filteredObject; } const desiredKeys = customObjectDescructurer(arr_of_keys, obj); console.log(desiredKeys);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.