0

I have an array of objects. I am trying to filter some objects from the array and get a new array using the following.

[
  {
    "userId": 1,
    "title": "title 1",
    "body": "Body for user 1",
    "address": {
      "country": "Germany",
      "state": "State1"
    },
    "phone": 1234
  },
  {
    "userId": 2,
    "title": "title 2",
    "body": "Body for user 2",
    "address": {
      "country": "Canada",
      "state": "State2"
    },
    "phone": 4321
  }
]

How can i filter the array and get the new array without address and phone. Any help is appreciated. Thank you

LearningToCode
  • 392
  • 5
  • 18
surazzarus
  • 772
  • 5
  • 17
  • 32
  • 1
    You literally dont show any attempts at anything. – Fallenreaper Jul 05 '18 at 17:59
  • You should post what you've tried so far. If you haven't tried anything yet, you should check out Array.prototype.map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map and report back. – wholevinski Jul 05 '18 at 17:59
  • @Derek `filter` will only include elements that pass the bool condition provided in filter. This problem is modifying the objects contained in the array, not filtering out elements of the array. Although I do agree with your sentiment of "please try and come up with something first" on such a low-effort post. – wholevinski Jul 05 '18 at 18:08

3 Answers3

3

You can use .map() and Object destructuring:

let data = [
    {"userId": 1, "title": "title 1", "body": "Body for user 1", "address": {"country": "Germany", "state": "State1"}, "phone": 1234},
    {"userId": 2, "title": "title 2", "body": "Body for user 2", "address": { "country": "Canada", "state": "State2"}, "phone": 4321}
];

let result = data.map(({address, phone, ...rest}) => rest);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Docs:

Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
0

You can use the .map method to create a new filtered array.

The map() method creates a new array with the results of calling a provided function on every element in the calling array

You can use a destructuring assignment to get and return the properties you wish to keep:

data.map(({userId, title, body}) => {
  return {userId, title, body}
});

Here's a demo:

const data = [
  {
    "userId": 1,
    "title": "title 1",
    "body": "Body for user 1",
    "address": {
      "country": "Germany",
      "state": "State1"
    },
    "phone": 1234
  },
  {
    "userId": 2,
    "title": "title 2",
    "body": "Body for user 2",
    "address": {
      "country": "Canada",
      "state": "State2"
    },
    "phone": 4321
  }
];

let res = [];
res = data.map(({userId, title, body}) => {
  return {userId, title, body}
});

console.log(res)
Ivan
  • 34,531
  • 8
  • 55
  • 100
0

You can also use reduce

let res = Object.values(data.reduce((c, {userId,title,body}) => {
      c[userId] = c[userId] || {userId, title, body}
      return c;
 }, {}));