Search code examples
javascriptobjectfrontenddata-manipulation

Extract specific properties and their values from an object


Let's say I have this obj:

let userInfo = {
    name: 'Ahmed',
    age: 24,
    _id: "34ef5576",
    email: '[email protected]'
}

how can i extract the properties name, _id, and email. And put them in a new Object? thanks.

So I want a simple way to solve this without any external libraries..!


Solution

  • I find it:

    1. let's say we have this Object, The original Object that we want to extract from its specific Fields:

      const parentObj = { name: "ahmed", age: 22, country: "morocco" };
      
    2. Now we are creating a function that creates for us the extract object:

      function pickFromObj(originalObject, arrayOfWantedProperties){
        let resultObj = {};
        for(property in originalObject){
          if(arrayOfWantedProperties.includes(property)){
            resultObj[property] = originalObject[property]
          }
        }
        return resultObj;
      }
      
    3. Finally Create the extract Object:

      let childObj = pickFromObj(parentObj, ['name', 'age']);