0

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 } ]

3 Answers 3

3

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)

Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

1

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);

Comments

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.