Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add index values of array in object to a key

Tags:

javascript

I have an object in variable info as :

0: {ProId: "Space", Name: "cake", Quantity: 1}
1: {ProId: "new", Name: "walk", Quantity: 1}

I am trying to change the Quantity value to it's index+1 for each index ,

I have tried to have a static value as:

  for (var key in obj){
    var value= obj[key];
    value['Quantity'] = 5;
  }

Expected O/p:

console.log(info)
    0: {ProId: "Space", Name: "cake", Quantity: 1}
    1: {ProId: "new", Name: "walk", Quantity: 2}
    2: {............................Quantity: 3}.....

But May I know how can I have the Quantity value as above mentioned

like image 902
Codenewbie Avatar asked Sep 19 '25 15:09

Codenewbie


2 Answers

Some hints:

  • Take an array instead of an object, if you need an easy iterable data structure. This gives control over the iteration order, too.
  • Use numbers for numeric values. If you need later a (formatted) string apply toString to it.

For getting a new value of a property, you could mutate the given data.

Using:

  • Array#forEach for visiting all items of the array,
  • an arrow function, a short form of a function.

var array = [{ ProId: "Space", Name: "cake", Quantity: "1" }, { ProId: "new", Name: "walk", Quantity: "1" }];

array.forEach((object, i) => object.Quantity = i + 1);

console.log(array);

Or get new objects by mapping the array.

Using:

  • Array#map for getting a new array,
  • spread syntax ... for taking all properties of an object into a new object

var array = [{ ProId: "Space", Name: "cake", Quantity: "1" }, { ProId: "new", Name: "walk", Quantity: "1" }],
    newArray = array.map((object, i) => ({ ...object, Quantity: i + 1 }));

console.log(newArray);
like image 53
Nina Scholz Avatar answered Sep 21 '25 04:09

Nina Scholz


You can map the array and return a new array but merging the old object with new object with updated Quantity value like:

const data = [{ProId: "Space", Name: "cake", Quantity: "1"}, {ProId: "new", Name: "walk", Quantity: "1"}],
  updatedData = data.map((x, i)=> ({...x, Quantity: ++i}));
 
console.log(updatedData)
.as-console-wrapper { max-height: 100% !important; top: 0; }

A simple example of updating an object key value (which is done here inside the map() method) is like:

let obj = { a: 0, b: 0};
let newObj = { ...obj, a: 1 };

console.log( newObj )
like image 44
palaѕн Avatar answered Sep 21 '25 05:09

palaѕн