简体   繁体   中英

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.

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

I think you want to do something like this. I'm assuming your data is an array of objects and not an object without keys, as you suggested.

const data = data.map((el, index) => {
    el.Key = index;
    return el;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM