0

I have an array like this

array = [
{
  id: 1,
  name: 'Apple',
  color: 'red
},
{
  id: 2,
  name: 'Orange',
  color: 'orange'
},
{
  id: 3,
  name: 'Banana',
  color:'yellow'
},
{
  id: 4,
  name: 'Malta',
  color:'orange'
}
];

and I just want to get "id" attribute from this array like this

 array = [
{
  id: 1,
},
{
  id: 2,
},
{
  id: 3,
},
{
  id: 4,
}
];

What should be the method to handle this situation. I tried filter method , map method but it didn't work

3
  • 1
    Show what you have tried, map should do the job just fine here. Commented Jan 11, 2019 at 9:38
  • For non-destructive way, map is the correct way. However, please show your code; note that "it didn't work" is a useless description (if it worked, you probably wouldn't be here, asking), and a good description of how, precisely it failed to work (with example input, example output and how it differs from the desired output) is much, much more useful. Commented Jan 11, 2019 at 9:39
  • You should be able to use map like array.map(x => x.id) Commented Jan 11, 2019 at 9:42

3 Answers 3

5

Use map operator to iterate over the array like this -

array.map(res => {return {id: res.id}})

PS - or Another shortcut way as @amadan suggested in comment

array.map(({id}) => ({id}))
Sign up to request clarification or add additional context in comments.

Comments

1

Use map on the array:

var initial = [{
    id: 1,
    name: 'Apple',
    color: 'red'
  },
  {
    id: 2,
    name: 'Orange',
    color: 'orange'
  },
  {
    id: 3,
    name: 'Banana',
    color: 'yellow'
  },
  {
    id: 4,
    name: 'Malta',
    color: 'orange'
  }
];

var finalArray = initial.map(item => {
  return {
    id: item.id
  }
});

console.log(finalArray);

Comments

0

You can use map to get the id property,

 arrayData.map(a => {
  return {
    id: a.id
  }
 })

var arrayData = [{
    id: 1,
    name: 'Apple',
    color: 'red'
  },
  {
    id: 2,
    name: 'Orange',
    color: 'orange'
  },
  {
    id: 3,
    name: 'Banana',
    color: 'yellow'
  },
  {
    id: 4,
    name: 'Malta',
    color: 'orange'
  }
];

const newarray = arrayData.map(a => {
  return {
    id: a.id
  }
})
console.log(newarray);

2 Comments

This funny syntax also works nicely: arrayData.map(({id}) => ({id}))
@Amadan yeah I know :D

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.