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).

3
  • @JonasWilms that is not the right duplicate. Commented Nov 13, 2018 at 20:54
  • @slides which would be better? Commented Nov 13, 2018 at 20:55
  • 1
    Perhaps stackoverflow.com/questions/17781472/… ? Commented Nov 13, 2018 at 20:56

1 Answer 1

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']));

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.