0

I want to loop through and add properties from an array to another array: Array1:

const users = [
   {
      "id":"112",
      "firstName":"a",
      "lastName":"b",
      "address":[
         {
            "apartment":"1",
            "street":"north"
         }
      ]
   },
   {
      "id":"113",
      "firstName":"e",
      "lastName":"f",
      "address":[
         {
            "apartment":"2",
            "street":"north"
         }
      ]
   },
   {
      "id":"114",
      "firstName":"i",
      "lastName":"j",
      "address":[
         {
            "apartment":"3",
            "street":"south"
         }
      ]
   },
   {
      "id":"1151",
      "firstName":"o",
      "lastName":"p",
      "address":[
         {
            "apartment":"4",
            "street":"west"
         }
      ]
   }
]

So, I have an empty array const usersInfo = [] I want to add only id and address in usersInfo from users array

What I am trying to do below:

    const result = this.usersInfo.map(item => {
  users.forEach((element) => {
    item.id = element.id,
    item.address = element.address.map(r => {
      return {
        apartment: r.apartment,
        street: r.street
      };
    }),
  });

});

But this returns an Empty array as a result.

I need output like below

const usersInfo = [
    {
      id: '112',
      address:[{
        apartment:'1',
        street: 'north'
      }]
},
      {
      id: '113',
      address:[{
        apartment:'2',
        street: 'north'
     }]
    },
    {
      id: '114',
      address:[{
        apartment:'3',
        street: 'south'
      }]
    },
    {
      id: '1151',
      address:[{
        apartment:'4',
        street: 'west'
      }]
   }
]
1
  • I assume address:[apartment:'1', street: 'north'] is supposed to be {apartment:'1', street: 'north'}? Please provide valid JSON in your question. Commented Jun 27, 2020 at 9:11

1 Answer 1

1

You can do something like below:

const usersInfo = users.map(user => ({id: user.id, address: user.address}))
Sign up to request clarification or add additional context in comments.

2 Comments

this is the optimum way!
If this solves the problem. You can accept it as your answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.