-1

I have an array of objects in them. I want to add two new properties to all objects in that array. The objects position in the array and the length of the array.

my code for this is:

 objArr.forEach(function(element) {
        element.data.basics.all= objArr.length, 
        element.data.basics.position= objArr.indexOf(element), 
    });

While in the forEach-loop the properties are added. I can print them while beeing in the loop. But after the loop has finished the properties are gone.

if have tried Add property to an array of objects but both, forEach and .map does not work.

I also tried:

 objArr.forEach(function(element) {
        element.data.basics.all= objArr.length, 
        element.data.basics.position= objArr.indexOf(element), 
        return element
    });

and

 objArr.map(function(element) {
   element.data.basics.position = objArr.indexOf(element)
       element.data.basics.all= objArr.length, 
        return element;
     }
 )

and i tried arrow function in all cases, so `...objArr.forEach((element)=>{...})

EliasPh
  • 43
  • 10
  • 3
    What *exactly* does "after the loop has finished" mean? What is the larger context of that `forEach`? Also there's no need for `.indexOf(element)`; the second parameter to the `.forEach()` callback is the index into the array, so you can just use that. – Pointy Mar 14 '19 at 16:10
  • 1
    **off-topic**: the second param to forEach is the index of the element, so you don't need `objArr.indexOf(element)` – Get Off My Lawn Mar 14 '19 at 16:10
  • 1
    Return inside `forEach` doesn't make any sense. and also things seems fine with the code you posted. you should post more code – Code Maniac Mar 14 '19 at 16:12
  • please add `objArr`. – Nina Scholz Mar 14 '19 at 16:12
  • 1
    Using your code, and what I assume your object structure looks like, I get `{ all: 1, position: 0 }` with one element in `objArr`... `let objArr = [{ data: { basics: { all: 0, position: -1 } } }]` – Get Off My Lawn Mar 14 '19 at 16:17

1 Answers1

0

It works fine with forLoop, new properties are added.

var array = [
        { person: { age: 76 }, state: 'ka' },
        { person: { age: 87 }, state: 'ap' },
        { person: { age: 45 }, state: 'tn' }
    ];
    array.forEach(function(element, index){
        element.person.length = array.length;
        element.person.index = index;
    });
    console.log(array)
Allabakash
  • 1,969
  • 1
  • 9
  • 15