Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating an existing object Array in ES6 javascript

I am a novice of ES6 JavaScript. I am looking for a scenario where i can update an object array that is coming from a web service and pass the data format to a table.

I am using ReactJS 'rc-table'.

https://www.npmjs.com/package/rc-table

To display our data in the rc-table format , We need to have an attribute key:"somevalue" in our data that is coming from the backend.

My data is in the following format:

{
 {
   Name:'Robert',
   City: 'Barcelona'
 },
 {
   Name: 'Marguaritte',
  City: 'Baltimore'

 }
}

Now it will display in rc-table format , only if the object has a unique key attribute.

For Example:

 {
 {
  Name:'Robert',
  City: 'Barcelona',
   Key:1
 },
 {
  Name: 'Marguaritte',
  City: 'Baltimore',
  Key:2

  }
 }

I am looking for updating my object with 'key:1' and 'key:2' Attached is my code. Any help would be appreciated.

like image 261
mohan babu Avatar asked Oct 26 '25 08:10

mohan babu


1 Answers

Well your actual array format is incorrect, you should replace wrapping {} with [] so it's a valid array.

Anyway you should use Array.prototype.map(), it will return a customised array using a callback function that will add the key property to each iterated item.

This is how you should write your code:

var data = arr.map(function(item, index) {
  item.key = index + 1;
  return item;
});

ES6 Solution:

Using ES6 arrow functions as suggested by Chester Millisock in comments:

var data = arr.map((item, index) => {
   item.key = index + 1;
   return item;
}); 

Demo:

var arr = [{
    Name: 'Robert',
    City: 'Barcelona'
  },
  {
    Name: 'Marguaritte',
    City: 'Baltimore'

  }
];

var data = arr.map((item, index) => {
   item.key = index + 1;
   return item;
}); 

console.log(data);
like image 186
cнŝdk Avatar answered Oct 28 '25 21:10

cнŝdk