-2
people: [
  {
    name: "Jon Doe",
    age: "25",
    city: "Detroit",
  },
  {
    name: "Jane Doe",
    age: "23",
    city: "Detroit",
  },
  {
    name: "Jack Doe",
    age: "22",
    city: "Detroit",
  },
  {
    name: "Joe Doe",
    age: "28",
    city: "Detroit",
  },
  {
    name: "Josh Doe",
    age: "27",
    city: "Detroit",
  }
]

TO THIS ------------>

anotherArray: [
  {
    name: "Jon Doe",
    city: "Detroit"
  },
  {
    name: "Jane Doe",
    city: "Detroit"
  },
  {
    name: "Jack Doe",
    city: "Detroit"
  },
  {
    name: "Joe Doe",
    city: "Detroit"
  },
  {
    name: "Josh Doe",
    city: "Detroit"
  }
]

How would I achieve this result? I just want to pull certain keys from each object, then make an object of those selected keys. Intuitively, I am thinking maybe the .map method but so far each attempt has been a failure.

NOTE: There is a similar question How to remove properties from an object array?. This is not a duplicate question, because I am not trying to DELETE anything from the object, and I attempting to create a new object with specific results.

4
  • people.map(x => {delete x.age; return x;}) Commented Feb 27, 2018 at 6:52
  • 1
    Share your attempt with map Commented Feb 27, 2018 at 6:54
  • @izengod delete mutates the original objects. Commented Feb 27, 2018 at 7:01
  • this is NOT a duplicate question. Commented Mar 1, 2018 at 1:57

2 Answers 2

2

I'd recommend using .map :

//Using your above people array:

people.map( ({name, city}) => ({name, city}) )

This should return the array you're looking for.

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

1 Comment

ahhh this solves the problem. Learned something today. Can't believe I didn't think to use .map this way originally.
0

Use .map on the array and inside the callback delete the key age.

var data = {
  people: [{
      name: "Jon Doe",
      age: "25",
      city: "Detroit",
    },
    {
      name: "Jane Doe",
      age: "23",
      city: "Detroit",
    },
    {
      name: "Jack Doe",
      age: "22",
      city: "Detroit",
    },
    {
      name: "Joe Doe",
      age: "28",
      city: "Detroit",
    },
    {
      name: "Josh Doe",
      age: "27",
      city: "Detroit",
    }
  ]
};

var newData = data.people.map(el => { delete el.age; return el; });

console.log(newData);

4 Comments

.... duh. Lmao thank you very much
Note that this modifies the original objects.
@JJJ thats correct! Thanks for mentioning...
Why downvotes? Care to explain?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.