0

I face the problem and I hope they will help me here with advice.

There is an array of objects. (urlParams.categories)

I want to output using the extension operator (...) not all of these objects in their entirety, but the specific value of these objects by key (id). i.e.: 1, 2, 3, 4, and so on

I can do this using "for in" or "forEach", but I'm want to know if it can be done with (...)

I tried to do it like this:

let urlParams = {
  'categories': [
    { id: '1', name: 'Test' },
    { id: '2', name: 'Test' },
    { id: '3', name: 'Test' },
    { id: '4', name: 'Test' }
  ]
}

console.log(urlParams.categories)
console.log(...urlParams.categories.id)

2 Answers2

1

You need to iterate over the categories to get the id:

const urlParams = {
  'categories': [
    { id: '1', name: 'Test' },
    { id: '2', name: 'Test' },
    { id: '3', name: 'Test' },
    { id: '4', name: 'Test' }
  ]
}

console.log(urlParams.categories.map(({id}) => id))
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
0

I can do this using "for in" or "forEach", but I'm want to know if it can be done with (...)

No, the ... called Spread. So from the definition on specs, everything you can do like this:

const categories = [...urlParams.categories];

to get an array of categories. After that, you have to use .map or something can loop such as for, forEach, reduce, etc.. to get exactly id of each category.

let urlParams = {
  'categories': [
    { id: '1', name: 'Test' },
    { id: '2', name: 'Test' },
    { id: '3', name: 'Test' },
    { id: '4', name: 'Test' }
  ]
};

const categories = [...urlParams.categories];
const result = categories.map(r => +r.id);
console.log(result);
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56