Assign ids to object of an array

I have tried this to assign id to objects of an array and the id is its index no. But forEach loop give me 0 for all index I don't know why but please help me complete this....

let allBloggerFeed = [{title, image, link, m_price, m_off, m_isAvail, cont}];
    allBloggerFeed.forEach((item, i) => {
     item.id = "product-" + i + 1;
})

allBloggerFeedis returning different Arrays not only one it's coming from API of blogger but when I tried to add ids in it like

[{id:{title, image, link, m_price, m_off, m_isAvail, cont}}

Then it's not working the forEach giving 0 for all

Please solve this.....

Upvotes: 0

Views: 1306

Answers (3)

Riccardo Colombo
Riccardo Colombo

Reputation: 1

To be honest I don't understand what you're exactly trying to do. The code you are using, will do something like this:

let array = [{a:'a',b:'b',c:'c'}, {d:'d',e:'e',f:'f'}, {g:'g',h:'h',i:'i'}]

array.forEach((item, i) => {
     item.id = "product-" + (i + 1);
})

console.log(array)

And give you something like this:

[
  { a: 'a', b: 'b', c: 'c', id: 'product-1' },
  { d: 'd', e: 'e', f: 'f', id: 'product-2' },
  { g: 'g', h: 'h', i: 'i', id: 'product-3' }
]

Is this what are you trying to do?

Upvotes: 0

spirift
spirift

Reputation: 3062

Try with a map rather than forEach. The map will return a new array with the modified values.

  const allBloggerFeed = [{title, image, link, m_price, m_off, m_isAvail, cont}];
  const feedWithIds = allBloggerFeed.map((item, i) => {
    return {
      ...item,
      id: "product-" + i + 1, 
    } 
  })

Upvotes: 2

Ravid
Ravid

Reputation: 303

Your allBloggerFeed variable is an array with 1 element. Notice: Your array has one element which is an object with properties (title, image...).

So when you invoke forEach() on that array - it will only run the loop once. And the only index you have is 1.

If you want all your objects (item, images...) to be in an array - just declare it differently:

let allBloggerFeed = [title, image, link, m_price, m_off, m_isAvail, cont];
  • without the {} brackets.

Upvotes: 0

Related Questions