1

Suppose I have an array of object, here I have assumed objects with three properties but it may be more and I want to extract some of them with property name:

objArr = [{
  name : "name",
  description : "description",
  date : "date"
},{
  name : "name",
  description : "description",
  date : "date"
},{
  name : "name",
  description : "description",
  date : "date"
}]

Say, I want to extract only value of name from aforementioned objArr. I am able to do it using:

(function(objArray){
  objArray.forEach(function(arrObjItem) {
    for(let name in arrObjItem) {
      if(arrObjItem.hasOwnProperty(name)) {
        console.log(objArrItem.name)
      }
    }
  })
})(objArr)

But what I really want is to extract value of name and description or value of more than two properties if the question has a different data structure with more properties to each object. Lastly I want to create a map of those extracted properties.(or a new array of objects with extracted property, value)(or a tuple with extracted property, value pair).

HarshvardhanSharma
  • 754
  • 2
  • 14
  • 28

1 Answers1

5

You could map the wanted keys of the object and generate a new object by mapping the array.

function getSubset(array, keys) {
    return array.map(o => Object.assign(...keys.map(k => ({ [k]: o[k] }))));
}

var objArr = [{ name: "name", description: "description", date: "date" }, { name: "name", description: "description", date: "date" }, { name: "name", description: "description", date: "date" }];

console.log(getSubset(objArr, ['name', 'description']));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392