RenJith
RenJith

Reputation: 557

Assign a key number to a key in the object by incrementing count

I have an array of objects . I need to convert the value of the 'key' by incrementing count .

lets say I have an array

const arr1=[{key:'a', val:1},{key:'b',val:2}]

I want to give an incrementing key value to each key

I have tried the below code but couldn't override the count value

   let count = 0;
   const arr1=[{key:'a', val:1},{key:'b',val:2}]
   arr1.map(el => el.key=count+1);
   console.log(arr1)

Expected Result : [ { key: 1, val: 1 }, { key: 2, val: 2 } ]

Upvotes: 0

Views: 41

Answers (3)

Jack Bashford
Jack Bashford

Reputation: 44145

Use ++ to update count while getting the new value. Also, you need to return the modified el from map, and make sure you assign the return value otherwise it'll be garbage-collected - map returns a new array.

let count = 0;

const arr1 = [{key:'a',val:1},{key:'b',val:2}];

const res = arr1.map(({ val }) => ({ key: ++count, val }));

console.log(res);

Upvotes: 1

adiga
adiga

Reputation: 35253

You could use forEach to loop through the array and update the key based on the index

const array = [ { key: 1, val: 1 }, { key: 2, val: 2 } ]
array.forEach((o, i) => o.key = i+1)
console.log(array)

If you want a new array you could use map like this:

const array = [ { key: 1, val: 1 }, { key: 2, val: 2 } ],
      newArray = array.map((o, i) => ({ ...o, key: i+1}));

console.log(newArray)

Upvotes: 3

CertainPerformance
CertainPerformance

Reputation: 371049

Because it looks like you want to perform side-effects rather than create a new array, use forEach instead of .map. You also need to actually increment the count variable on each iteration:

let count = 0;
const arr1=[{key:'a', val:1},{key:'b',val:2}]

arr1.forEach(el => {
  count++;
  el.key = count;
});
console.log(arr1)

Upvotes: 2

Related Questions